-1

I want to add constraints to a view programmatically.

This is what I did:

extension UIView {
  func bottomToTop(other: UIView) {
     self.translatesAutoresizingMaskIntoConstraints = false
     other.translatesAutoresizingMaskIntoConstraints = false
     let constraint = NSLayoutConstraint(
        item: self,
        attribute: .bottom,
        relatedBy: .equal
        toItem: other,
        attribute: .top,
        multiplier: 1.0,
        constant: 0.0
    )
    superview?.addConstraint(constraint)
    constraint.isActive = true
  }
}


let label = UILabel()
label.text = "Lenaaaaa"
label.sizeToFit()
label.backgroundColor = .green

let label1 = UILabel()
label1.text = "Lena 2"
label1.sizeToFit()
label1.backgroundColor = .green

let uiView = UIView(frame: frame) (not zero)
uiView.addSubview(label)
uiView.addSubview(label2)

label.bottomToTop(label2)

Why do I end up with this?

enter image description here

1 Answer 1

1

Why do I end up with this?

Because your constraints are ambiguous. Once you add even one constraint that affects a view, you must describe that view's position and size in terms of autolayout completely. (And you must stop talking about .frame, as it is now effectively meaningless.)

Thus, you have said only

label.bottomToTop(label2)

But you have not said where the top of label is, where the left of label is, where the left of label2 is, and so on. Thus the autolayout engine throws up its hands in despair.

You could easily have discovered this just by running your app and using the view debugger. It puts up great big exclamation marks telling you what your autolayout issues are.

Sign up to request clarification or add additional context in comments.

2 Comments

Also your code is wrong in various other ways. For instance you should never say both addConstraint and constraint.isActive = true; they do the same thing, and the second one does it way better.
Plus your code makes no sense to me because it talks about a uiView that never even goes into the interface, so I do not understand why you say anything. If this is playground code, stop it; use a real project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.