iOS 7まではUIAlertViewを利用してアラート制御をしていたのですが,iOS 8からはUIAlertControllerを利用してアラート制御することが推奨されています。
UIAlertControllerを使ってどのようにアラート制御するのか整理しました。
開発環境
Xcode Ver 8.2.1-
Swift 3.0
iOS 10.2
iPhone 7 Plus Simulator
UIAlertController実装の手順
実装の手順をコードだけでなく,図でも表しましたので参考にして下さい。
let コントローラー名 = UIAlertController(title: "アラートのタイトル",message: "アラートの説明", preferredStyle: UIAlertControllerStyle.alert)
let 部品名 = UIAlertAction(title: "部品名", style:UIAlertActionStyle.default){
(action: UIAlertAction) in
// 以下はボタンがクリックされた時の処理
print("Hello")
}
コントローラー名.addAction(部品名)
present(コントローラー名,animated: true, completion: nil)
サンプルコード
ViewController.swift
import UIKit
class 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)
}
}
実行結果
実行結果は以下のようになります。
以上,Swift3.0でアラートを制御する方法でした。