带文本的文本字段中的退格键会导致崩溃

时间:2022-04-11 15:34:38

I have a text field that is being checked for a lowercase letter, uppercase, number, and special character. When i type each of them in it does what it is supposed to do. However if i delete a character it crashes. I'm pretty sure it has to do with the 0, but I am not sure what to do about it

我有一个文本字段正在检查小写字母,大写,数字和特殊字符。当我在其中键入每个内容时,它会执行它应该执行的操作。但是,如果我删除一个字符,它会崩溃。我很确定它与0有关,但我不知道该怎么做

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

    let newText = range.length == 0 ? roomPasscode.text! + string : (roomPasscode.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

    let hasUppercaseCharacters = newText.hasUppercaseCharacters()
    let hasLowercaseCharacters = newText.hasLowercaseCharacters()
    let hasNumberCharacters = newText.hasNumberCharacters()
    let hasSpecialCharacters = newText.hasSpecialCharacters()
    let isTenCharactersLong = newText.characters.count == 10

    oneUpperMet.textColor = hasUppercaseCharacters ? .greenColor() : .redColor()
    oneLowerMet.textColor = hasLowercaseCharacters ? .greenColor() : .redColor()
    oneNumMet.textColor = hasNumberCharacters ? .greenColor() : .redColor()
    oneSpecialMet.textColor = hasSpecialCharacters ? .greenColor() : .redColor()
    tenCharMet.textColor = isTenCharactersLong ? .greenColor() : .redColor()



    if hasUppercaseCharacters && hasLowercaseCharacters && hasNumberCharacters && hasSpecialCharacters && isTenCharactersLong {
        clickableButton.tintColor = UIColor.greenColor()
    }

    return true
}

1 个解决方案

#1


1  

The else parameter of this ternary:

这个三元的else参数:

let newText = range.length == 0 ? roomPasscode.text! + string : (roomPasscode.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

is trying to delete a non-existent character. Try just leaving it like this for a quick fix:

正在尝试删除不存在的字符。试着像这样离开它以便快速修复:

let newText = range.length == 0 ? roomPasscode.text! + string : roomPasscode.text!

#1


1  

The else parameter of this ternary:

这个三元的else参数:

let newText = range.length == 0 ? roomPasscode.text! + string : (roomPasscode.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

is trying to delete a non-existent character. Try just leaving it like this for a quick fix:

正在尝试删除不存在的字符。试着像这样离开它以便快速修复:

let newText = range.length == 0 ? roomPasscode.text! + string : roomPasscode.text!