用于切换文本字段的最大长度

问题描述 投票:0回答:2

我有几个文本字段,每个文本字段具有不同数量的最大字符。如何将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
2个回答
2
投票
 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
}
© www.soinside.com 2019 - 2024. All rights reserved.