Add UITextField with constraints programmatically
<p>In my application I want to add one or more UITextFields with button clicking. I can create UITextFields inside a custom UIView (predefined in Storyboard), but I can't properly Add constraints to the text field and constraint for UIView against Button (button is locating under the UIView). So with every button click I want to resize the UIView with given constraints and move button down after adding the text field. now I'm using this code, it adds text fields successfully, but constraints are not working:</p>

<pre><code>@IBAction func addCustomTextField(sender: AnyObject) {

    let x : CGFloat = 20
    var y : CGFloat = 10
    let width : CGFloat = 300
    let height : CGFloat = 40


    var lastButtonY : Int? = NSUserDefaults.standardUserDefaults().integerForKey("lastButtonY")

    if lastButtonY &gt; 0 {
        y = CGFloat.init(lastButtonY! + 8)
        NSUserDefaults.standardUserDefaults().setObject(y + height, forKey: "lastButtonY")
    } else {
        NSUserDefaults.standardUserDefaults().setObject(10 + height, forKey: "lastButtonY")
    }

    sampleTextField = UITextField(frame: CGRectMake(x, y, width, height) )
    sampleTextField.placeholder = "Enter text here"
    sampleTextField.font = UIFont.systemFontOfSize(15)
    sampleTextField.borderStyle = UITextBorderStyle.RoundedRect
    sampleTextField.autocorrectionType = UITextAutocorrectionType.No
    sampleTextField.keyboardType = UIKeyboardType.Default
    sampleTextField.returnKeyType = UIReturnKeyType.Done
    sampleTextField.clearButtonMode = UITextFieldViewMode.WhileEditing;
    sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
    self.customView.addSubview(sampleTextField)

    let bottomConstraintForTextField = NSLayoutConstraint(item: sampleTextField, attribute: .Bottom, relatedBy: .Equal, toItem: customView, attribute: .Bottom, multiplier: 1, constant: 10)

    let bottomConstraintForCustomView = NSLayoutConstraint(item: customView, attribute: .Bottom, relatedBy: .Equal, toItem: addButton, attribute: .Bottom, multiplier: 1, constant: 10)

    NSLayoutConstraint.activateConstraints([bottomConstraintForTextField, bottomConstraintForCustomView])

}
</code></pre>