user2640633
user2640633

Reputation:

Backspace in textfield with text causes crash

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

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
}

Upvotes: 1

Views: 543

Answers (1)

Julian Lee
Julian Lee

Reputation: 263

The else parameter of this ternary:

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!

Upvotes: 0

Related Questions