0

Just trying to add a UILabel using SnapKit autolayout. The code i'm using is as follows:

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .lightGray

    let userNameLabel = UILabel()
    userNameLabel.text = "Dinesh nagarajan"
    userNameLabel.backgroundColor = .white
    self.view.addSubview(userNameLabel)

    userNameLabel.snp.makeConstraints { (make) in
        make.top.leading.trailing.height.equalTo(40)

    }
}

Here i have mentioned the constraints for leading and trailing equals to 40. But the result i'm getting is different than the code. I have attached the image for reference to the code above. Why is it behaving differently than expected...?

Constrain mismatch

DonMag
  • 69,424
  • 5
  • 50
  • 86
Dinesh Nagarajan
  • 1,063
  • 2
  • 10
  • 22
  • What are the actual auto-layout constraint values when you run / debug the app? Is it "clipped" at the right edge, or extending *past* the edge? If you haven't yet, use Debug View Hierarchy to inspect the elements. – DonMag Sep 25 '17 at 19:38
  • @DonMag it's clipping at the right edge. – Dinesh Nagarajan Sep 25 '17 at 19:49
  • I don't use SnapKit, but it *looks* like a problem with the trailing constraint. What happens if you remove the `.trailing` part, and add a second line that says: `make.trailing.equalTo(-40)` ? – DonMag Sep 25 '17 at 19:55
  • If i remove the trailing constrain it's taking the width of the label. But if i add `make.trailing.equalTo(-40)` the label fit exactly as expected. – Dinesh Nagarajan Sep 25 '17 at 19:59
  • OK - so the problem is: you were first setting the `.trailing` constraint to be "the right edge of the superview **plus** 40 pts" but you really need it to be "the right edge of the superview **minus** 40 pts". – DonMag Sep 25 '17 at 20:01

1 Answers1

0
userNameLabel.snp.makeConstraints { (make) in
    make.top.leading.trailing.equalTo(view).inset(40)
    make.height.equalTo(40)
}

Seems like an issue with the constraints themselves. If you use the inset for the positioning and set an explicit height it should work a bit better.

cherbear
  • 253
  • 2
  • 3
  • 11