So, I'm done using the IB in Xcode and want to write all UI in Swift.
So what I've done is:
- Created a new
UIViewto contain the elements i want to write - lets call it "TestView" - I've added
TestViewto aVCas a sub view. In the
TestViewclass 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) } }
With this I expect the UILabel to be anchored to the right side of the view.
However, I do get this error:
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.'
What am I doing wrong?
