【问题标题】:Create a view of the same size of a super view in Swift 3在 Swift 3 中创建与超级视图相同大小的视图
【发布时间】:2017-02-15 07:38:38
【问题描述】:

我正在尝试使用设置背景颜色和不透明度的视图在图像顶部创建蒙版,它似乎在 iPhone 7 中运行良好。当我在 iPhone 中运行应用程序时出现问题7 plus 模拟器,由于某种原因,面具保持 iPhone 7 尺寸的大小。

我创建了一个自定义 UIImageView 类:

class LoginBackgroundImageView: UIImageView {

    override func awakeFromNib() {
         super.awakeFromNib()

         // Set a mask on image background
         let bgColorView = UIView()
         bgColorView.backgroundColor = UIColor(white: 0, alpha: 0.4)
         bgColorView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)

         addSubview(bgColorView)
     }
}

目前的结果是这样的:

【问题讨论】:

  • bgColorView.frame = CGRect(x: 0, y: 0, width: yourimage.frame.width, height: yourimage.frame.height) 不知道这个框架来自哪里?我假设您在框架中设置硬编码值。
  • 或者添加self.frame
  • 试试这个bgColorView.frame = frame
  • 你试过设置约束吗??

标签: ios iphone swift swift3


【解决方案1】:

在将 bgColorView 添加为 subView 后尝试将约束添加到框架中。

class LoginBackgroundImageView: UIImageView {

    override func awakeFromNib() {
        super.awakeFromNib()
        self.clipsToBounds = true // set clipsToBounds true

        let bgColorView = UIView()
        bgColorView.backgroundColor = UIColor(white: 0, alpha: 0.4)
        addSubview(bgColorView)

        bgColorView.translatesAutoresizingMaskIntoConstraints = false

        bgColorView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        bgColorView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
        bgColorView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        bgColorView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    }
}

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    你试过了吗:

    bgColorView.frame = frame 
    

    或者:

    bgColorView.frame = UIScreen.main.bounds
    

    【讨论】:

    • 第二种解决方案确实有效;但是,视图覆盖了整个屏幕,我正在使用相同的代码将蒙版放在不填满整个屏幕的其他图像上。第一个解决方案不起作用。
    【解决方案3】:

    您的LoginBackgroundImageViewContent Mode 是否可能与AspectFitScaleAspectFit 不同?在这种情况下,可能是图像实际上超出了其框架,而 bgColorView 具有正确的框架。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多