所以,我已经在 Xcode
中使用了 IB
,并且想在 Swift 中编写所有 UI
。
所以我所做的是:
- 创建了一个新的
UIView
以包含我要编写的元素 - 我们称它为“TestView” - 我已将
TestView
作为 subview 添加到VC
。 在
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
锚定到 View 的右侧。
但是,我确实遇到了这个错误:
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.'
我做错了什么?
最佳答案
只有在将 View 添加到 View 层次结构后才应添加约束。从您的代码中可以清楚地看出您没有添加要查看的 UILabel 实例。
关于iOS 在 Swift 中以编程方式添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40839981/