因此,我完成了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爲您的視圖的子視圖?您只能應用約束,並在已添加爲子視圖時將其激活。否則嘗試會導致崩潰,你只看到 –