Ios 将字符限制指定给特定UITextField
以下代码可以工作,但适用于所有文本字段。如何将其限制为一个特定的文本字段 代码:Ios 将字符限制指定给特定UITextField,ios,swift,uitextfield,Ios,Swift,Uitextfield,以下代码可以工作,但适用于所有文本字段。如何将其限制为一个特定的文本字段 代码: func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let currentCharacterCount = (textField.text?.characters.count) ?? 0 if
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
}
func textField(textField:UITextField,shouldChangeCharacters范围:NSRange,replacementString:string)->Bool{
让currentCharacterCount=(textField.text?.characters.count)??0
if(range.length+range.location>currentCharacterCount){
返回错误
}
让newLength=currentCharacterCount+string.characters.count-range.length
返回newLength两个选项
1) 只为一个文本字段实现您在UITextFieldDelegate
实现中引用的代码。我非常喜欢这个选项
2) 有条件地检查唯一标识您感兴趣的文本字段的内容,例如其标记
属性。仅对该文本字段运行字符计数检查。否则,默认为true
我从不使用tag属性来标识UI元素,也不建议使用它。但是,我看到它经常被使用
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Set textField tag to 9 if you want pass this guard
guard textField.tag == 9 else {
return true
}
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
}
func textField(textField:UITextField,shouldChangeCharacters范围:NSRange,replacementString:string)->Bool{
//如果要通过此防护,请将textField标记设置为9
guard textField.tag==9 else{
返回真值
}
让currentCharacterCount=(textField.text?.characters.count)??0
if(range.length+range.location>currentCharacterCount){
返回错误
}
让newLength=currentCharacterCount+string.characters.count-range.length
return newLength假设您有两个文本字段,并且您的控制器是这两个字段的委托
@IBOutlet var aMagesticTextField: UITextField!
@IBOutlet var anotherMagesticTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
aMagesticTextField.delegate = self
anotherMagesticTextField.delegate = self
}
在shouldChangeCharactersIn中,对照已知的文本字段检查textField参数
if textField == aMagesticTextField {
//It's aMagesticTextField
}
else {
//It's anotherMagesticTextField
}
谢谢这正是我需要的