Allow only alphanumeric characters for a UITextField

前端 未结 7 972
野性不改
野性不改 2020-11-27 17:44

How would I go about allowing inputting only alphanumeric characters in an iOS UITextField?

7条回答
  •  盖世英雄少女心
    2020-11-27 18:17

    Swift 3 version

    Currently accepted answer approach:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        // Get invalid characters
        let invalidChars = NSCharacterSet.alphanumerics.inverted
    
        // Attempt to find the range of invalid characters in the input string. This returns an optional.
        let range = string.rangeOfCharacter(from: invalidChars)
    
        if range != nil {
            // We have found an invalid character, don't allow the change
            return false
        } else {
            // No invalid character, allow the change
            return true
        }
    }
    

    Another equally functional approach:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        // Get invalid characters
        let invalidChars = NSCharacterSet.alphanumerics.inverted
    
        // Make new string with invalid characters trimmed
        let newString = string.trimmingCharacters(in: invalidChars)
    
        if newString.characters.count < string.characters.count {
            // If there are less characters than we started with after trimming
            // this means there was an invalid character in the input. 
            // Don't let the change go through
            return false
        } else {
            // Otherwise let the change go through
            return true
        }
    
    }
    

提交回复
热议问题