title: Adding a subview and position it with constraints programmatically
body: <p>I have added a <code>UIView</code> using the IB on to the view controller. Let's call it the <code>redView</code>. </p>
  
  <p><img src="https://i.stack.imgur.com/yJQkgm.png" alt="enter image description here"></p>
  
  <p>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.</p>
  
  <p><img src="https://i.stack.imgur.com/C1A6rm.png" alt="enter image description here"></p>
  
  <p>Now I want to add a <code>UILabel</code> to this view programmatically and position it in the center using auto layout constraints.</p>
  
  <p>Below is the code I have so far.</p>
  
  <pre><code>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])
  
      }
  
  }
  </code></pre>
  
  <p>The problem is the label doesn't appear on the <code>redView</code>. Can anyone please tell me what I'm missing here?</p>
  
  <p>Thank you.</p>