如何限制UItextField的长度和特殊字符?

时间:2015-08-06 12:52:08

标签: ios swift uitextfield

我可以使用下面的代码限制长度,但我似乎无法找到限制特殊字符的方法。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = count(textField.text.utf16) + count(string.utf16) - range.length
if (textField.placeholder == "USERNAME")
{
    //Also limit special characters here
    return newLength <= 15 // Bool
}

我想要的字符:

  

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 _

我尝试按照link进行操作,但是它在目标C中,我在将其与目前的15个字符限制代码合并时遇到问题

2 个答案:

答案 0 :(得分:3)

除了正则表达式之外,您可以先将所有允许的字符放入集合中:

 var charactesAllowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."
 var charactersSet = [Character](charactesAllowed)

然后尝试查看最近输入的字符是否在此数组中

var newCharacter = //whatever the character is, ex: "A"
if(contains(charactersSet, newCharacter))
{
    println("Allowed")
    // Add it into the label text
}

答案 1 :(得分:-2)

let  ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"


if textField == textFieldNumber{
            let characterSet = CharacterSet.init(charactersIn: ACCEPTABLE_CHARACTERS).inverted
            maxLength = 11
            let currentString: NSString = textField.text! as NSString
            let newString: NSString =
                currentString.replacingCharacters(in: range, with: string) as NSString
            let filter = string.components(separatedBy: characterSet).joined(separator:"")
            return ((string == filter) && newString.length <= maxLength!)
        }