LoginSignup
5
5

More than 5 years have passed since last update.

UITextFieldで入力チェックする(Swift2.2)

Last updated at Posted at 2016-03-31

UITextField入力チェックする場合のメモ

結論

UITextFieldTextDidChangeNotificationを使う。
これで入力中も判定できる。

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    // Swift2.2の場合
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.changeTextField(_:)), name: UITextFieldTextDidChangeNotification, object: nil)
    // Swift2.1の場合
    // NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeTextField:", name: UITextFieldTextDidChangeNotification, object: nil)
}

func changeTextField (sender: NSNotification) {
    let text = sender.object as! UITextField
    print(text)
}

失敗

これだと入力確定後の判定となり一文字目が判定できない

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
   print(textField)
   return true
}
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5