swift - 限制同一VC中两个不同文本字段的文本字符
我想让一个文本字段只允许有人输入10个字符,而在第二个文本字段中他们可以输入20个字符而不知道如何将其放入一个应该更改字符func中,因为我猜你不做两个单独的功能,因为这对我不起作用?
//文字字段1
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentCharacterCount = textfield1.text?.characters.count ?? 0
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
return newLength <= 10
}
// text field 2
func textField2(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentCharacterCount2 = TextField2.text?.characters.count ?? 0
if (range.length + range.location > currentCharacterCount2){
return false
}
let newLength = currentCharacterCount2 + string.characters.count - range.length
return newLength <= 20
}
答案 0 :(得分:2)
如果视图中的两个文本字段都有插座,那么您可以执行以下操作:
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
var maxLength = 0
if textField.isEqual(textField1) {
maxLength = 10
} else if textField.isEqual(textField2) {
maxLength = 20
}
return newLength <= maxLength
}
只需将两个文本字段名称替换为您的出口名称:)