しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

【Swift, UIActionController】アクションシートで外側のビューを押された時のイベント

アクションシートで外側のビュー(下の灰色部分)を押された時のイベント周りについて調べてみました。

f:id:llcc:20170905141224p:plain

キャンセルボタンがある場合、外側のビューを押すとアクションシートは閉じます。
その際、キャンセルボタンが押された時と同じ処理が呼び出されます。

import UIKit

class ViewController: UIViewController {
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        let c = UIAlertController(title: nil, message: "めっせーじ", preferredStyle: .actionSheet)
        c.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        c.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: { action in
            print("cancelled") // → 外側のビューをタップ or キャンセルボタンタップでここが呼ばれる
        }))
        
        present(c, animated: true, completion: nil)
    }
}

handlerにnilを渡しても、同じようにアクションシートは閉じます。

let c = UIAlertController(title: nil, message: "めっせーじ", preferredStyle: .actionSheet)
c.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
c.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))

キャンセルボタンがない場合は、外側のビューを押してもアクションシートが消えなくなります。

f:id:llcc:20170905141545p:plain

let c = UIAlertController(title: nil, message: "めっせーじ", preferredStyle: .actionSheet)
c.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

キャンセルボタンを2つセットしようとすると、下のようなエラーが出てアプリがクラッシュします。

UIAlertController can only have one action with a style of UIAlertActionStyleCancel
let c = UIAlertController(title: nil, message: "めっせーじ", preferredStyle: .actionSheet)
c.addAction(UIAlertAction(title: "キャンセル1", style: .cancel, handler: nil))
c.addAction(UIAlertAction(title: "キャンセル2", style: .cancel, handler: nil))

アクションシートをアラートに置き換えても、同じようにエラーになります。

let c = UIAlertController(title: nil, message: "めっせーじ", preferredStyle: .alert)
c.addAction(UIAlertAction(title: "キャンセル1", style: .cancel, handler: nil))
c.addAction(UIAlertAction(title: "キャンセル2", style: .cancel, handler: nil))