Swift 3 - 将TextField限制为字母数字(带有空格和超量)

时间:2017-05-23 00:22:00

标签: swift input whitespace textfield alphanumeric

想要将Textfield输入限制为仅限A-Z,a-z,0-9," "和 - 。目前有:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        if self.isNumericTextInput{
            let allowedCharacters = CharacterSet.decimalDigits
            let characterSet = CharacterSet(charactersIn: string)
            if allowedCharacters.isSuperset(of: characterSet) && returnFlag{
                return true
            } else{
                return false
            }

        } else{
            // Allow only alphanumerics, whitespace and hyphens
        }
        return
    }

2 个答案:

答案 0 :(得分:4)

虽然回答很晚,但对某人可能有用。

斯威夫特3:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    /// 1. replacementString is NOT empty means we are entering text or pasting text: perform the logic
    /// 2. replacementString is empty means we are deleting text: return true
    if string.characters.count > 0 {
        var allowedCharacters = CharacterSet.alphanumerics
        allowedCharacters.insert(charactersIn: " -") // "white space & hyphen" 

       let unwantedStr = string.trimmingCharacters(in: allowedCharacters)
       return unwantedStr.characters.count == 0
    }

    return true
}

注意:这也适用于将字符串粘贴到文本字段中。如果粘贴的字符串包含任何不需要的字符,则不会在文本字段中显示。

答案 1 :(得分:0)

试试这个:

UnicastRemoteObject