Edited at

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

More than 3 years have passed since last update.


はじめに


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では非推奨!!(ヽ;ω;)