ios - swift - 限制同一 VC 中两个不同文本字段上的文本字符

标签 ios swift xcode

<分区>

swift - 限制同一 VC 中两个不同文本字段上的文本字符

我想让一个文本字段只允许某人输入 10 个字符,而在第二个文本字段中他们可以输入 20 个字符,只是不确定如何将其放入一个 shouldchangecharacter 函数中,因为我猜你不会做两个单独的功能,因为这对我不起作用?

//文本域 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

}

//文本域 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

}

最佳答案

如果您的 View 中有两个文本字段的导出,那么您可以这样做:

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

}

只需将两个文本字段名称替换为您的网点名称:)

关于ios - swift - 限制同一 VC 中两个不同文本字段上的文本字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44211569/

相关文章:

ios - 设备 [iPhone] 如何与单个外围设备绑定(bind) [蓝牙低功耗设备]

ios - iOS 如何自动检测网络打印机

ios - 如何在 Swift 的类级别制作一组 UIImageViews?

iphone - 什么是自动布局?

objective-c - 设置自定义 UIPickerView

ios - 我怎样才能完全忽略整个应用程序中的时区?

ios - CGImageCreateWithMaskingColors没有匹配的函数

ios - 使用 UIWebView 从服务器播放视频不起作用

ios - shouldPerformSegueWithIdentifier 不适用于 SWRevealViewController

ios - 2 个根据内部文本调整大小并同时具有相等宽度的 UIButton?