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

时间:2016-05-07 10:26:23

标签: swift

我有一个正在检查小写字母,大写,数字和特殊字符的文本字段。当我输入它们中的每一个时它会做它应该做的事情。但是,如果我删除一个字符,它会崩溃。我很确定它与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 个答案:

答案 0 :(得分:1)

这个三元的else参数:

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

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

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