那么,我已经不再使用Xcode
中的IB
,希望能够用Swift编写所有的UI
。
所以我做的事情是:
- Created a new
UIView
to contain the elements i want to write - lets call it "TestView" - I've added
TestView
to aVC
as a sub view. In the
TestView
class I've added the elements like this: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
锚定在视图的右侧。
然而,我遇到了以下错误:
未捕获异常“NSGenericException”,原因是“无法激活具有项目>和>的约束,因为它们没有共同的祖先。
是否约束引用了不同视图层次结构中的项目? 这是非法的。'
我做错了什么?