【问题标题】:how to set the maximum 4 digit number in uitextfield using swift3.0如何使用swift3.0在uitextfield中设置最大4位数字
【发布时间】:2017-12-13 18:10:55
【问题描述】:

我使用此代码,但它应该返回任何人。但是我需要使用这两个场景。那么我该如何改变呢?任何人都可以帮助我。我限制了一个(.0 符号,同时只允许 4 位数。我该怎么做呢???

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard let text = amountField.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
    return newLength <= 4 // Bool

   let ACCEPTABLE_CHARACTERS = "1234567890"
    let cs = CharacterSet(charactersIn: ACCEPTABLE_CHARACTERS).inverted
    let filtered: String = string.components(separatedBy: cs).joined(separator: "")
    return string == filtered



}

【问题讨论】:

    标签: swift3 uitextfield swift4


    【解决方案1】:

    您的问题的可能解决方案。

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        var newLength = string.utf16.count - range.length
    
        if let text = textfield.text {
            newLength = text.utf16.count + string.utf16.count - range.length
        }
    
        let characterSet = NSMutableCharacterSet()
        characterSet.addCharacters(in: "1234567890")
    
        if string.rangeOfCharacter(from: characterSet.inverted) != nil || newLength > 4 {
            return false
        }
        return true
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2018-03-12
      • 2015-09-30
      • 2010-09-30
      • 2011-02-01
      • 1970-01-01
      • 2014-12-22
      相关资源
      最近更新 更多