NSAlert でメッセージを表示する

NSAlert を使って、メッセージを表示してアクションを求める方法をメモする。サンプルのスクリプトの中でも使ってるけど、まあ、ちょっと書き残してみる。

基本的には、できることは、Alert メッセージを表示すること。それには、まず、NSAlertalertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat を使って Window の設定をする。これで、alert メッセージ、default button のテキスト、other button のテキスト、other button のテキスト、informative テキストを指定する。そして、runModal で、この Window を表示する。そのときの返り値は、Default Button が 1、Alternate Button が 0、Other Button が -1 になる。

これをスクリプトにしてみると、次のようになる。

alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat("Title Text","Default","Alternate","Other","Informative Text")

userChoice = alert.runModal

case userChoice

when 0

#action for "Alternate" button

when 1

#action for "Default" button

when -1

#action for "Other" button

end

これを実行すると、次のような表示になる。

alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat で、最低限 Default Button のテキストを設定すれば動くはず(Default Button も nil だと OK と表示のあるボタンが出る)。alert メッセージと、informative テキストは、表示させない場合はブランクの String オブジェクトを入れる。つまり "" でいい。ボタンは表示させない場合は nil を指定する。"" だと文字の表示のないボタンが表示される。

この他に、Save/Open パネルと同様に、setAccessoryView(view) で Accessory View を表示できる。詳しいことは Accessory View を Interface Builder で作るを参照してください。

この他に、Save/Open パネルと同様に、Window から出てくるようにもできる。その場合は、beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo を使う。これで、alert を出す window、delegate、ボタンがクリックされたときに実行するメソッド、context info を指定する。最後は使い方がわからないので、nil でやっているが、わかったらまた追加する。この辺りも、詳しいことは Save パネル を参照してください。実行するメソッドは、何でもいいんだろうけど、3つの情報が返ってくる。実行された NSAlert オブジェクト、返り値(どのボタンがクリックされたか)、それと、context info。デベロッパドキュメントの例で alertDidEnd_returnCode_contextInfo(panel,returnCode,info) となっているので、それにする。

def alert(sender)

alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat("TitleText","Default","Alternate","Other","Informative Text")

alert.setAccessoryView(@view)

alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo(@window,self,"alertDidEnd_returnCode_contextInfo",nil)

end

ib_action :alert

def alertDidEnd_returnCode_contextInfo(panel,returnCode,info)

case returnCode

when 0

#action for "Alternate" button

when 1

#action for "Default" button

when -1

#action for "Other" button

end

end

これで、accessory view にアクセスしたいときは、NSAlert の accessoryView というメソッドを使って、panel.accessoryView とする。ここで、追加したパーツに何らかの目印を付けておけば、その情報にもアクセスできるはず。まあ、最初から outlet として指定しておけば問題は少ないが。