问题
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.
回答1:
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)
}
回答2:
@the4kman gave the correct answer, but you can add constraints easier by using the height anchor:
textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 100))
来源:https://stackoverflow.com/questions/46171757/how-can-i-change-the-height-of-uitextfield-in-uialertcontroller-in-swift