因此,我完成了Xcode
中的IB
并且想要在Swift中编写所有UI
。IOS以编程方式在Swift中添加约束条件
所以我所做的就是:
- 创建一个新的
UIView
包含我想写的元素 - - 我添加
TestView
到VC
为让称它为“TestView”子视图。 在
TestView
类我已经添加的元素是这样的:class TestView: UIView { var someLabel:UILabel! override init(frame: CGRect) { super.init(frame: frame) self.someLabel = UILabel(frame: CGRect(x: self.frame.midX, y: oneSixthHeight, width: 100, height: 22)) self.someLabel.text = "test" var constraints:[NSLayoutConstraint] = [] self.someLabel.translatesAutoresizingMaskIntoConstraints = false let rightsideAnchor:NSLayoutConstraint = NSLayoutConstraint(item: self.someLabel, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 1) constraints.append(rightsideAnchor) NSLayoutConstraint.activateConstraints(constraints) } }
有了这个,我期待UILabel
锚定到视图的右侧。
不过,我得到这个错误:
Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with items > and > because they have no common ancestor.
Does the constraint reference items in different view hierarchies? That's illegal.'
我在做什么错?
你在哪里添加someLabel为您的视图的子视图?您只能应用约束,并在已添加为子视图时将其激活。否则尝试会导致崩溃,你只看到 –