【问题标题】:maxLength for switch text field切换文本字段的 maxLength
【发布时间】:2020-09-22 05:56:09
【问题描述】:

我有几个文本字段,每个字段的最大字符数不同。如何将 if 分支更改为枚举并使用 switch?

 //if -> switch
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newLength = (textField.text ?? "").count + string.count - range.length

        if(textField == textFieldA) {
            return newLength <= 6
        }
        if(textField == textFieldB) {
            return newLength <= 7
        }
        if(textField == textFieldC) {
            return newLength <= 8
        }
        return true
    }

【问题讨论】:

    标签: ios swift if-statement switch-statement conditional-statements


    【解决方案1】:
     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            let newLength = (textField.text ?? "").count + string.count - range.length
            switch textField {
               case textFieldA :
                   return newLength <= 6
               case textFieldB:
                   return newLength <= 7
               case textFieldC:
                  return newLength <= 8
               default:
                  return true 
            }
    }
    

    【讨论】:

    • 请在您的答案中添加解释,因为纯代码的答案不太有用
    【解决方案2】:

    您正在使用 == 将一个字段与多个字段进行比较,因此您应该能够像下面这样:

    switch (textField) {
       case textFieldA:
           return newLength <= 6
       case textFieldB:
           return newLength <= 7
       case textFieldC:
           return newLength <= 8
       default:
           return true
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多