【发布时间】:2015-09-07 06:53:13
【问题描述】:
我一直在尝试为我的应用设计一个可重用的组件。它主要用于学习目的。
我试图以编程方式设置约束,但 Interface Builder 不断添加自动约束:
<NSIBPrototypingLayoutConstraint:0x7fae02731800 'IB auto generated at build time for view with fixed frame' H:[_1.TOHeader:0x7fae02718c20(89)]>
这打破了我的。
这是我的代码:
import UIKit
class TOHeader: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
println("init aDecoder")
self.backgroundColor = UIColor(red: 255, green: 0, blue: 0, alpha: 1)
self.setTranslatesAutoresizingMaskIntoConstraints(false)
}
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
println("willMoveToSuperview()")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
superview!.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Left, relatedBy: .Equal, toItem: superview!, attribute: .Left, multiplier: 1.0, constant: 0.0))
superview!.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: .Equal, toItem: superview!, attribute: .Width, multiplier: 1.0, constant: 0.0))
addConstraint(NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 42))
}
}
【问题讨论】:
-
首先你应该给你的 TOHeader 添加顶部约束。
-
刚刚尝试添加这个顶级约束:
addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 0.0)),它确实让我的应用程序崩溃 -
您的顶级约束在超级视图或其他视图之间没有关系,请尝试像
superview!.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: .Equal, toItem: superview!, attribute: .Top, multiplier: 1.0, constant: 0.0)) -
效果很好,谢谢。但是宽度和高度约束仍然没有被应用,因为它们被
Interface Builder打破了。任何想法 ?也许有更好的方法 -
一般来说,我更喜欢在超级视图中添加约束而不是在视图中。当您将 TOHeader 添加到您的视图时,您应该在调用
addSubview:方法后添加您的约束