将字符限制分配给特定的UITextField [英] Assigning Character Limit to a Specific UITextField
本文介绍了将字符限制分配给特定的UITextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码有效,但适用于所有TextField.如何将其限制为一个特定的TextField?
The following code works but applies to all TextFields. How can I limit it to one specific TextField?
代码:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentCharacterCount = (textField.text?.characters.count) ?? 0
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
return newLength <= 9
}
推荐答案
假定您有两个textField,并且您的控制器是这两个的委托.
Assuming that you have two textFields and your controller is a delegate of both.
@IBOutlet var aMagesticTextField: UITextField!
@IBOutlet var anotherMagesticTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
aMagesticTextField.delegate = self
anotherMagesticTextField.delegate = self
}
在shouldChangeCharactersIn中,对照您已知的文本字段检查textField参数.
In shouldChangeCharactersIn, check the textField parameter against your known text fields.
if textField == aMagesticTextField {
//It's aMagesticTextField
}
else {
//It's anotherMagesticTextField
}
这篇关于将字符限制分配给特定的UITextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文