简体   繁体   中英

How can I change the height of UITextField in UIAlertController in Swift?

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.

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)
}

添加约束的结果

@ the4kman给出了正确的答案,但是你可以通过使用高度锚来更容易地添加约束:

textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 100))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM