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

不羁岁月 提交于 2019-12-17 20:14:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!