我正在尝试以编程方式在警报 View 内创建一个限制为 100 个字符的大尺寸文本字段。这是我的代码:
func alertWithTF() {
let alert = UIAlertController(title: Constants.cancelPopupTitle,
message: Constants.cancelPopupMessage,
preferredStyle: .alert)
alert.addTextField { (textField) in
textField.frame = CGRect(x: 20, y: 100, width: 300, height: 80)
textField.placeholder = "Please enter message"
textField.borderStyle = UITextField.BorderStyle.line
textField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
}
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
guard let textfield = alert?.textFields?.first else { return }
let message = textfield.text ?? ""
print(message)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
self.present(alert, animated: true, completion: nil)
}
这是我的问题:
- 我想通过编辑文本字段的框架来修改文本字段的高度,但它似乎不起作用。
- 我还想设置文本字段的限制字符<= 100,但我找不到方法。
我可以使用任何可能的解决方案吗?感谢您帮助我。
最佳答案
UIAlertController 是不可自定义的。您可以针对这种情况创建自己的alertViewController,然后按照您想要的方式使用UI。
在您的 addTextfield 中,向 self 提供委托(delegate)
alert.addTextField { (textField) in textField.frame = CGRect(x: 20, y: 100, width: 300, height: 80) textField.placeholder = "Please enter message" textField.borderStyle = UITextField.BorderStyle.line textField.delegate = self textField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center }
并且您可以使用shouldChangeCharactersIn方法来限制长度
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLimit = 180
let currentString = textField.text!
let newString: String =
currentString.replacingCharacters(in: range, with: string) as String
return newString.length <= maxLength
}
确保您的 ViewController 符合 UITextFieldDelegate。
class YourViewController: UIViewController, UITextFieldDelegate {
}
关于swift - 在 Alertview 中快速创建和自定义 UITextfield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59210733/