2017-07-26 4 views
-2

textFieldの文字数が6になったときに何らかのアクションを実行したい。私のUITextFieldの長さが6文字に達するとすぐにメソッドを呼び出す方法

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) 

、その後は

func textFieldDidChange(_ textField: UITextField) { 
    if textField.text?.characters.count == 6 { 
     // Call some method 
    } 
} 
+0

使用するUITextField/UITextViewの委任方法のUITextField/UITextViewの公式ドキュメンテーションに – radkrish

+0

REFERE –

答えて

4

使用デリゲートは、あなたは範囲を使用して長さだけでなく、位置を取得するためにshouldChangeCharactersInRangeを使用することができます。

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

    let text = (textField.text ?? "") as String 
    let txtAfterUpdate = text.replacingCharacters(in: range, with: string) 
    if (text.characters.count == 6 && range.location > 5) { 
     return false // if you want to restrict your string length of call some method here 
    } 
    return true 
} 
関連する問題