本文介绍了限制UITextField中的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到了很多答案,但似乎没有一个有效.我有一个带有两个UITextField的以编程方式创建的UIAlertView.我想限制字符数:
I've seen a lot of answers, but it seems that none of them has worked.I have a programmatically created UIAlertView with two UITextFields.I want to restrict the number of characters :
- 第一个字段中的12个字符
- 第二个字段中有1个字符
第一个域代码:
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
}
如何正确限制数量(假设这些字段中没有粘贴)
How can I correctly restrict the number (Let's pretend that there will be no paste in these field)
推荐答案
将textField委托设置为相应的类(在我的情况下,自身是ViewController)
Set textField delegates to respective class (in my case self is ViewController)
nameField.delegate = self
keyField.delegate = self
然后您可以通过以下方式限制字符
Then you can restrict characters by
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
}
}
这篇关于限制UITextField中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!