iOSアプリでボタンを押してアラートを表示してみる

iOSアプリでボタンを押してアラートを表示してみる。


ボタンを設置。

右上のアシスタントエディタのボタンを押して、コードの画面を表示し、
ボタンを右クリックして、ドラッグする。

Actionを選択して、名前を入力し、[Connect]を押すと、

メソッドが追加される。

アラートを表示するコードを記入する。

let alertController = UIAlertController(title: "test", message: "Hello, world!", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)

presentViewController(alertController, animated: true, completion: nil)

実行して、ボタンを押すとアラートが表示される。


ちなみに、Main.storyboardのxmlには、下記のような感じでconnectionsタグが追加されている。

・・・
<connections>
    <action selector="helloWorld:" destination="・・・" eventType="touchUpInside" id="・・・"/>
</connections>
・・・

テキストフィールドに入力された文字列をアラートで表示してみる

テキストフォールドを設置。

右クリックでドラッグする。

適当な名前をつける。

messageの所を修正する。

let alertController = UIAlertController(title: "test", message: "Hello, world!", preferredStyle: .Alert)

let alertController = UIAlertController(title: "test", message: aaa.text, preferredStyle: .Alert)

実行し、テキストフィールドに適当に文字を入力してボタンを押すと、アラートに表示される。