LoginSignup
30
31

More than 5 years have passed since last update.

SwiftでUIAlertController(iOS8以降)とUIAlertView(iOS7以前)を使い分ける

Last updated at Posted at 2015-01-16

Swiftでアラートを出す場合、ios7に対応するにはUIAlertViewを使う必要があります。
選択肢が2つ(キャンセル、OK)のアラートの場合について書きます。

まずUIAlertViewを使うのに、UIViewControllerにUIAlertViewDelegateを追加しておきましょう。(アラートの選択肢2つ以上の場合にUIAlertViewDelegateが必要です。)

class MainViewController: UIViewController, UIAlertViewDelegate {
    //以下省略

objc_getClassでUIAlertControllerクラスがあるかどうかチェックします。

    if objc_getClass("UIAlertController") != nil {
            //UIAlertController使用
            var ac = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)

            let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in
                println("Cancel button tapped.")
            }

            let okAction = UIAlertAction(title: "OK", style: .Default) { (action) -> Void in
                println("OK button tapped.")
            }

            ac.addAction(cancelAction)
            ac.addAction(okAction)

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

        } else {
            //UIAlertView使用
            var av = UIAlertView(title: "Title", message:"Message", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
            av.show()
        }

UIAlertViewでボタンが押されたアクション用のメソッドも追加しておきましょう。

    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if (buttonIndex == alertView.cancelButtonIndex) {
            //Canceled
        } else {
            //OK
        }
    }
30
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
31