在@IBDesignable
,
我正在尝试以编程方式设置“父级的20%宽度”:
@IBDesignable
class TwentyPercentExample:UIView {
func setup() {
let cWidth = NSLayoutConstraint(
item: self,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.superview,
attribute: NSLayoutAttribute.width,
multiplier: 0.2,
constant:0
)
addConstraint(cWidth)
print("I seemed to added the width constraint....")
updateConstraintsIfNeeded() // could be useful..
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
}
(所以,你要在故事板中添加一个UIView,或者将它固定在左边的superview上,然后将类更改为TwentyPercentExample。)
奇怪的是,这不起作用。如果你这样做:
multiplier: 1,
constant:100
它很好地将它设置为实时,在故事板中达到100宽度。改为
multiplier: 1,
constant:200
并且工作正常,将其实时更改为200宽度。然而,这似乎不起作用:
multiplier: 0.2,
constant:0
我有toItem:
错了,还是什么?这是什么交易?
答案 0 :(得分:2)
我怀疑问题是,当init
为self.superview
时,您在nil
内执行此操作。您应该等待添加约束,直到将其添加到超级视图中。也许在didMoveToSuperview()
中,虽然这可能会变得混乱,因为您需要考虑这样一个事实,即它可以多次添加到超级视图中。
固定常量大小写起作用的原因可能是因为它的合法性有一个约束,用nil
项作为toItem:
参数硬编码为100。
所以,这些
中的任何一个override func didMoveToSuperview() { setup() }
... or ...
override func layoutSubviews() { setup() }
func setup() {
self.widthAnchor
.constraint(equalTo: superview!.widthAnchor, multiplier: 0.2)
.isActive = true
}
似乎工作:但似乎不规律地工作并且生成了代理人崩溃" Xcode中的错误。