Text Field ちょっと応用
ここでは、Text Field に関して、ちょっとした応用みたいなことをまとめていく。
Text Field のテキストの変更をとらえる
Text Field に何か文字を入力したりするときに、何も文字が入力されていない場合はボタンを使えなくする、なんてことをしたいときに、Text Field のテキストの変更をとらえる方法。
まず、変更をとらえたい Interface Builder で、Text Field の delegate をスクリプトを書いているクラスのインスタンスに結びつける。
そうすると、NSControlTextDidChangeNotification というのが発せられるので、それを controlTextDidChange という delegate メソッドでとらえる。
ib_outlet :textField
def controlTextDidChange(notification)
end
これで、notification の object で、delegate が結びつけてある Text Field の情報が来るので、これを notification.object.to_s でとらえて処理する。
def controlTextDidChange(notification)
case notification.object.to_s
when @textField.to_s
処理を書く
end
end
処理としては、@button というボタンを設定しておくとして、Text Field に文字が入力されていない状態で使えなくしておき、文字が入力されれば使えるようにしてみる。
def controlTextDidChange(notification)
case notification.object.to_s
when @textField.to_s
if @textField.stringValue.to_s == ""
@button.setEnabled(false)
else
@button.setEnabled(true)
end
end
end
これで、文字が Text Field になければボタンが使えなくなり、文字が入力されていれば使えるようになる。
まあ、Object Controller を使ったりすれば Binding でいけそうな気もするけど、まだ使い方がよくわからないので、とりあえず動く、という方法。