2016-05-07 49 views
1

我有一個正在檢查小寫字母,大寫字母,數字和特殊字符的文本字段。當我輸入它們中的每一個時,它都會做它應該做的事情。但是,如果我刪除了一個字符,它會崩潰。我敢肯定,它與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 
} 
+0

能詳細解釋一下你的實際需要 –

+0

我需要能夠挖掘刪除按鈕,而不應用程序崩潰 – RubberDucky4444

回答

1

這三元的其他參數:

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!