【问题标题】:UIView from NIB not conforming to parent constraints after adding autolayout constraints添加自动布局约束后,NIB 中的 UIView 不符合父约束
【发布时间】:2016-11-06 14:41:30
【问题描述】:

我正在使用以下方法将我的 NIB 文件加载到我的视图中:

override init(frame: CGRect) {        
    super.init(frame: frame)
    Bundle.main.loadNibNamed("EventPopup", owner: self, options: nil)
    //self.frame = self.view.bounds - DIDN'T WORK
    //self.frame.size.width = 300 - DID'T WORK
    self.addSubview(self.view);    // adding the top level view to the view hierarchy
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    Bundle.main.loadNibNamed("EventPopup", owner: self, options: nil)
    self.addSubview(self.view);    // adding the top level view to the view hierarchy
}

这有效并添加了我的 NIB,但 UIView 的宽度延伸到父容器之外。这仅在将自动布局添加到 uiview 后发生。我检查过,初始帧大小为 600x600。

即使在尝试通过调用 layoutSubviews() 来重置 NIB 大小并将新的框架约束放入其中之后,仍然拒绝调整大小。例如:

override func layoutSubviews() {
   // self.frame.size.width = 300
    //self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: 200, height: self.frame.height)
}

【问题讨论】:

    标签: swift autolayout nib


    【解决方案1】:

    看看这个帖子here。查看第三个技巧,它展示了如何创建从 nib 加载的视图。代码转载如下(免责声明它是用 Swift 2 编写的):

    @IBDesignable
    class ProfileView: UIView {
       @IBOutlet var imgView: UIImageView!
       @IBOutlet var labelOne: UILabel!
       @IBOutlet var labelTwo: UILabel!
       override init(frame: CGRect) {
          super.init(frame: frame)
          setUp()
       }
       required init?(coder aDecoder: NSCoder) {
          super.init(coder: aDecoder)
          setUp()
       }
       func setUp() {
          let bundle = NSBundle(forClass: self.dynamicType)
          let nib = UINib(nibName: “Profile”, bundle: bundle)
          let viewFromNib = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
          addSubview(viewFromNib)
          viewFromNib.translatesAutoresizingMaskIntoConstraints = false
          self.addConstraints(
             NSLayoutConstraint.constraintsWithVisualFormat(
                “H:|[v]|”, 
                options: NSLayoutFormatOptions(rawValue: 0), 
                metrics: nil, 
                views: [“v”:viewFromNib]
             )
          )
          self.addConstraints(
             NSLayoutConstraint.constraintsWithVisualFormat(
                “V:|[v]|”, 
                options: NSLayoutFormatOptions(rawValue: 0), 
                metrics: nil, views: [“v”:viewFromNib]
             )
          )
       }
    }
    

    一旦您在代码和笔尖中正确设置了它,您应该能够轻松地对其进行初始化。在界面生成器或代码中:

    // 视图控制器

    override viewDidLoad() {
        super.viewDidLoad()
        self.addSubview(ProfileView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)))
    }
    

    【讨论】:

    • 帖子在哪里?
    • 对不起,我添加了链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多