我已经看到很多答案,但似乎没有一个有效。 我有一个以编程方式创建的带有两个UITextField的UIAlertView。 我想限制字符数:
第一个字段代码:
alertDialog.addTextField { (nameField) in
nameField.placeholder = "Name"
nameField.borderStyle = .roundedRect
nameField.clearButtonMode = .whileEditing
}
第二次
alertDialog.addTextField { (keyField) in
keyField.placeholder = "Key"
keyField.borderStyle = .roundedRect
keyField.clearButtonMode = .whileEditing
}
如何正确限制数字(让我们假装这些字段中没有粘贴)
答案 0 :(得分:3)
将textField委托设置为相应的类(在我的情况下,self是ViewController)
nameField.delegate = self
keyField.delegate = self
然后你可以通过
来限制字符extension ViewController : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
switch textField {
case nameField:
if ((textField.text?.length)! + (string.length - range.length)) > 12 {
return false
}
case keyField:
if ((textField.text?.length)! + (string.length - range.length)) > 1 {
return false
}
}
return true
}
}
答案 1 :(得分:0)
您可以添加如下事件:
textField1.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)
textField2.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)
然后实现这个功能:
func textFieldDidChange(textField: UITextField) {
if textField == self.textField1 && textField.text.length > 12 {
// Do whaterver you want
}
if textField == self.textField2 && textField.text.length > 1 {
// Do whaterver you want
}
}