LoginSignup
4

More than 5 years have passed since last update.

【iOS8非推奨】Swiftで単純なアラート制御(UIAlertViewDelegateの実装)

Last updated at Posted at 2014-12-16

はじめに

Important: UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is also deprecated.)
(あのね、これiOS8では非推奨になってるから。)

(え)

iOS8推奨版に書きなおしました

OK・キャンセル

import UIKit

class ViewController: UIViewController , UIAlertViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    @IBAction func tapButton(sender: UIButton) {
        let alert: UIAlertView! = UIAlertView(
                    title: "Confirm",
                    message: "OK/Cancel",
                    delegate: self,
                    cancelButtonTitle: "Cancel",
                    otherButtonTitles: "Ok")
        alert.show()
    }

    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 0 {
            NSLog("pushed Cancel Button")
        } else if buttonIndex == 1 {
            NSLog("pushed OK Button")
        }
    }
}

3択(寿司・ラーメン・断食)

import UIKit

class ViewController: UIViewController ,UIAlertViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func tapButton(sender: UIButton) {
        let alert: UIAlertView! = UIAlertView(
                    title: "どちらかえらべ",
                    message: "食べます",
                    delegate: self,
                    cancelButtonTitle: "断食",
                    otherButtonTitles: "寿司", "ラーメン")
        alert.show()
    }

    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 0 {
            NSLog("(ヽ´ω`)ぎゅるるぅぅ。。。")
        } else if buttonIndex == 1 {
            NSLog("?")
        } else if buttonIndex == 2 {
            NSLog("?")
        }
    }
}

要点

  1. UIAlertViewDelegateプロトコル宣言
  2. Action時に、alert作成と、実行
  3. alertViewの実装
  4. iOS8では非推奨!!(ヽ;ω;)

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
4