【问题标题】:swift - limit text characters on two different textfields in the same VC [duplicate]swift - 在同一 VC 中的两个不同文本字段上限制文本字符 [重复]
【发布时间】:2017-05-26 23:54:33
【问题描述】:

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

}

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    如果您的视图中的两个文本字段都有出口,那么您可以执行以下操作:

    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
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-09
      • 2017-07-05
      • 2013-10-23
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多