添加自动布局约束后,来自NIB的UIView不符合父约束

时间:2016-11-06 14:41:30

标签: swift autolayout nib

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

>>> import re
>>> re.findall('[0-9]+', "b'197,2302,50,198,\r\n'")
['197', '2302', '50', '198']

这可以并且添加我的NIB,但是UIView的宽度在父容器之外延伸。只有在向uiview添加autolayout后才会出现这种情况。我检查过,初始帧大小为600x600。

即使尝试通过调用layoutSubviews()重置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
}

1 个答案:

答案 0 :(得分:2)

看一下这篇文章here。查看第3个提示,其中显示了如何创建从笔尖加载的视图。代码在下面转载(免责声明,它是用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]
         )
      )
   }
}

在代码和笔尖中正确设置后,您应该能够轻松初始化它。在“接口”构建器或代码中:

// ViewController

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