6

I have added a UITextField in a UIAlertController. I want to change the height of the text field. I have tried this way:

let alertController = UIAlertController(title: "Comments", message: "Write your comments here", preferredStyle: UIAlertControllerStyle.alert)
alertController.addTextField { (textField : UITextField) -> Void in
    var frame: CGRect = textField.frame
    frame.size.height = 100
    textField.frame = frame
    textField.placeholder = "comment"
    print(textField.frame.size.height)
}

let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (result : UIAlertAction) -> Void in
}

let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
}

alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)

It's not working.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Ilias Ahmed
  • 105
  • 3
  • 9

2 Answers2

23

This works with a constraint.

alertController.addTextField { textField in
    let heightConstraint = NSLayoutConstraint(item: textField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
    textField.addConstraint(heightConstraint)
}

result of adding the constraint

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • is there also a way to "hide" one text field? Simply setting its height constraint to 0 doesn't work. – Tobe Dec 19 '19 at 11:13
12

@the4kman gave the correct answer, but you can add constraints easier by using the height anchor:

textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 100))
Daniel Illescas
  • 5,346
  • 3
  • 17
  • 23