iOS 7まではUIAlertViewを利用してアラート制御をしていたのですが,iOS 8からはUIAlertControllerを利用してアラート制御することが推奨されています。
UIAlertControllerを使ってどのようにアラート制御するのか整理しました。
開発環境
*Xcode Ver 8.2.1-* *Swift 3.0* *iOS 10.2* *iPhone 7 Plus Simulator*UIAlertController実装の手順
実装の手順をコードだけでなく,図でも表しましたので参考にして下さい。
サンプルコード
```swift:ViewController.swift import UIKitclass ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// アラートボタンがクリックされた時の実装
@IBAction func tapAlertButton(_ sender: Any) {
// ① コントローラーの実装
let alertController = UIAlertController(title: "test",message: "アラートボタン", preferredStyle: UIAlertControllerStyle.alert)
// ②-1 OKボタンの実装
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){ (action: UIAlertAction) in
// ②-2 OKがクリックされた時の処理
print("Hello")
}
// CANCELボタンの実装
let cancelButton = UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.cancel, handler: nil)
// ③-1 ボタンに追加
alertController.addAction(okAction)
// ③-2 CANCELボタンの追加
alertController.addAction(cancelButton)
// ④ アラートの表示
present(alertController,animated: true,completion: nil)
}
}
<h2>実行結果</h2>
実行結果は以下のようになります。
<img width="414" alt="Simulator Screen Shot 2017.03.31 20.09.41.png" src="https://qiita-image-store.s3.amazonaws.com/0/145535/348389c6-e583-b6ee-4b9c-28071f1c69e1.png">
以上,Swift3.0でアラートを制御する方法でした。