Ios 限制UITextfield长度会限制我的所有UITextfields

Ios 限制UITextfield长度会限制我的所有UITextfields,ios,swift,uitextfield,swift2,Ios,Swift,Uitextfield,Swift2,我有一个UITextField,我想将长度限制为4个字符以下是代码: func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { guard let text = acRegTextField.text else { return true } let newL

我有一个UITextField,我想将长度限制为4个字符以下是代码:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        guard let text = acRegTextField.text else { return true }

        let newLength = text.utf16.count + string.utf16.count - range.length
        return newLength <= 4 // Bool
    }
func textField(textField:UITextField,shouldChangeCharactersRange:NSRange,replacementString:string)->Bool{
guard let text=acRegTextField.text else{return true}
让newLength=text.utf16.count+string.utf16.count-range.length
return newLength这是来自的一个方法。要使此方法有效,您必须在某个地方说过

myTextField.delegate = myClass
您所说的每个文本字段都将获得相同的委托。如果您不希望限制应用于某个特定的文本字段,则不要为该文本字段设置委托。

这是来自的一种方法。要使此工作正常,您必须在某个地方说过

myTextField.delegate = myClass

您所说的每个文本字段都将获得相同的委托。如果您不希望限制应用于特定的文本字段,则不要为该文本字段设置委托。

如果您的视图中有许多文本字段并将委托分配给它们,则应更改字符范围将应用于所有文本字段。因此,您可以做的是:s如果您已经有一个文本字段的出口,该出口应仅包含4个字符-然后只需比较此文本字段就是您要验证的文本字段-注意===比较引用。例如:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if acRegTextField === textField {
        guard let text = acRegTextField.text else { return true }

        let newLength = text.utf16.count + string.utf16.count - range.length
        return newLength <= 4 // Bool
    }
    return true
}
func textField(textField:UITextField,shouldChangeCharactersRange:NSRange,replacementString:string)->Bool{
如果acRegTextField===textField{
guard let text=acRegTextField.text else{return true}
让newLength=text.utf16.count+string.utf16.count-range.length

return newLength如果视图中有多个文本字段,并将委托分配给这些字段,则shouldChangeCharactersRange将应用于所有文本字段。因此,如果您已经有一个文本字段的出口,该出口应仅包含4个字符,则只需将此文本字段与您要验证的文本字段进行比较即可。注意e==比较引用。例如:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if acRegTextField === textField {
        guard let text = acRegTextField.text else { return true }

        let newLength = text.utf16.count + string.utf16.count - range.length
        return newLength <= 4 // Bool
    }
    return true
}
func textField(textField:UITextField,shouldChangeCharactersRange:NSRange,replacementString:string)->Bool{
如果acRegTextField===textField{
guard let text=acRegTextField.text else{return true}
让newLength=text.utf16.count+string.utf16.count-range.length

return newLength非常好的答案,我知道我必须以某种方式将其包装在if语句中,但无法找出它是什么。解释很棒,让我更了解它。非常好的答案,我知道我必须以某种方式将其包装在if语句中,但无法找出它是什么。解释很棒,让我更了解它