LoginSignup
2
1

More than 5 years have passed since last update.

UIAlertControllerで押されたアクションのインデックスを得る

Last updated at Posted at 2018-04-30

UIAlertControllerで表示したAlertもしくはActionSheetで、押されたボタンをインデックスで判断したい時は以下のようにすると良いでしょう。

let controller = UIAlertController(title: "アプリ開発言語", 
                                   message: "どの言語でアプリを開発してますか?",
                                   preferredStyle: .actionSheet)
// ここでlet actions = controller.actionsにすると空の状態でhandler内で参照されるので注意
var actions = [UIAlertAction]()
let handler = { (action: UIAlertAction) in
    // UIAlertController#actionsから押されたUIAlertActionのindexを得る
    if let index = actions.index(of: action) {
        print("index:\(index) title:\(action.title!)")

        // 最後のボタンはキャンセル
        if index == actions.count - 1 {
            print("cancel")
        }
    }
}
controller.addAction(UIAlertAction(title: "Swift", style: .default, handler: handler))
controller.addAction(UIAlertAction(title: "Kotlin", style: .default, handler: handler))
controller.addAction(UIAlertAction(title: "Objective-C", style: .default, handler: handler))
controller.addAction(UIAlertAction(title: "Java", style: .default, handler: handler))
controller.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: handler))
// UIAlertActionを追加しきった後で代入すること
actions = controller.actions
present(controller, animated: true, completion: nil)

注意すべきは、handler関数でUIAlertControllerを参照すると、UIAlertControllerがUIAlertActionを経由してhandlerを参照するため循環参照になって、メモリリークすることです。(UIAlertControllerのdeinitが呼ばれません)。よって、handler内ではcontroller.actionsのように参照せずにactionsを参照しています。

2
1
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
2
1