I have added a UIView
using the IB on to the view controller. Let's call it the redView
.
Then I have pinned its all four sides using auto layout constraints in code and when I run it, it looks like this as expected.
Now I want to add a UILabel
to this view programmatically and position it in the center using auto layout constraints.
Below is the code I have so far.
import UIKit
class ViewController: UIViewController {
@IBOutlet private var redView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
redView.setTranslatesAutoresizingMaskIntoConstraints(false)
let leadingConstraint = NSLayoutConstraint(item: redView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: redView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint(item: redView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: redView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)
view.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
let label = UILabel()
label.text = "Auto Layout Exercise"
redView.addSubview(label)
let xCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: redView, attribute: .CenterX, multiplier: 1, constant: 0)
let yCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: redView, attribute: .CenterY, multiplier: 1, constant: 0)
let leadingConstraint1 = NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: redView, attribute: .Leading, multiplier: 1, constant: 20)
let trailingConstraint1 = NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: redView, attribute: .Trailing, multiplier: 1, constant: -20)
redView.addConstraints([xCenterConstraint, yCenterConstraint, leadingConstraint1, trailingConstraint1])
}
}
The problem is the label doesn't appear on the redView
. Can anyone please tell me what I'm missing here?
Thank you.
I'm pretty sure you need to also set:
label.setTranslatesAutoresizingMaskIntoConstraints(false)
Otherwise I don't think the constraints will apply to the label.
Note for Swift 2/3
It has changed to Boolean property: UIView.translatesAutoresizingMaskIntoConstraints
Instead of it previously being:
label.setTranslatesAutoresizingMaskIntoConstraints(false)
It is now:
label.translatesAutoresizingMaskIntoConstraints = false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With