UITextField内の文字が変更される度に関数を呼び出す
iOSアプリ開発で、UITextField 内の文字が変更される度に関数を呼び出すことをできるようにします。そのためには NSNotificationCenter クラスを使います。
開発環境
完成予定図
TextFieldないの文字が変わる度に、コンソールに文字を出力します。
UITextField 内の文字が変更されたことを知るために
UITextField 内の文字が変わったらこの関数を実行してくれと、NSNotificationCenter クラスにお願いをします。以下のコードを ViewWillAppear メソッド内に書きます。
// ViewWillAppear メソッド内
NSNotificationCenter.defaultCenter().addObserver( self,
selector: Selector("何らかの関数:"),
name: UITextFieldTextDidChangeNotification,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver( self,
selector: Selector("何らかの関数:"),
name: UITextFieldTextDidChangeNotification,
object: nil
)
何らかの関数に、コンソールに「変わったよ」と表示する関数を指定してみます。
// Selector("何らかの関数:") を Selector("textFieldDidChange:")に変更
func textFieldDidChange(aNotification: NSNotification) {
print("変わったよ")
}
func textFieldDidChange(aNotification: NSNotification) {
print("変わったよ")
}
View に UITextField を乗っけただけのアプリで動作確認をしてみます。
これで完了です!
おわりに
今回は addObserver の name 引数に UITextFieldTextDidChangeNotification を指定しましたが、他にもこのような定数が沢山用意されています。例えば、「キーボードが表示されるよ」を表す UIKeyboardDidShowNotification があります。これらは各クラスのリファレンスの下部に Notifications としてまとめられています。