Search code examples
iosswift3nslayoutconstraint

Swift, constraint, UILabel, anchor right


Desired...

enter image description here

For some reason the following doesn't work:

extension UIView {
    func addWordOnRight() {
        let l = UILabel()

        //l.frame = self.bounds ..?

        l.textAlignment = .right
        l.text = "blah"

        self.addSubview(l)

        let m = self.layoutMarginsGuide
        l.trailingAnchor.constraint(equalTo: m.trailingAnchor, constant: 0).isActive = true
        l.centerYAnchor.constraint(equalTo: m.centerYAnchor, constant: 0).isActive = true
    }
}

And if you l.frame = self.bounds, it mysteriously anchors to the left, not right.


Solution

  • By default the label has translatesAutoresizingMaskIntoConstraints set to true, so the view automatically adds constraints. When you add your own constraints these conflict with those already added. (You should be seeing lots of warnings in your console.)

    If you want to use autolayout set l.translatesAutoresizingMaskIntoConstraints = false. Your constraints should now work correctly.

    In case you also want to set the width and height of the label, set those using constraints as well (leave the frame alone).