どこからでも呼び出せるようにして、ボタンをおした時の挙動は呼び出し側で定義するできるようにしてみる
アラート表示用の汎用クラス
以下をコピペ
/** アラート表示クラス */
class Alert: NSObject {
/** 確認メッセージを表示する */
static func show(
title title: String,
withMsg msg:String ) {
// UIAlertControllerクラスのインスタンスを生成
// タイトル, メッセージ, Alertのスタイルを指定する
// 第3引数のpreferredStyleでアラートの表示スタイルを指定する
let alert: UIAlertController = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)
// Alertを表示 最全面のViewControllerの取得
var tc = UIApplication.sharedApplication().keyWindow?.rootViewController;
while ((tc!.presentedViewController) != nil) {
tc = tc!.presentedViewController;
}
tc.presentViewController(alert, animated: true, completion: nil)
}
/**
キャンセル・OKを持つシンプルなアラート
```
// 使用例
let ok :Void -> Void = {
print("OK")
}
Alert.show(
title: "title",
withMsg: "msg",
okAction: ok,
cancalAction: { print("cancel") })
```
*/
static func show(
title title: String,
withMsg msg:String,
okAction ok:Void -> Void,
cancalAction cancel:Void -> Void) {
// タイトル, メッセージ, Alertのスタイル
let alert: UIAlertController = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)
// OKボタン
let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{
(action: UIAlertAction!) -> Void in
ok()
})
// キャンセルボタン
let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertActionStyle.Cancel, handler:{
(action: UIAlertAction!) -> Void in
cancel()
})
alert.addAction(cancelAction)
alert.addAction(defaultAction)
// Alert表示 最全面のViewControllerの取得
var tc = UIApplication.sharedApplication().keyWindow?.rootViewController;
while ((tc!.presentedViewController) != nil) {
tc = tc!.presentedViewController;
}
tc.presentViewController(alert, animated: true, completion: nil)
}
}
アラート表示用の汎用クラスの使用方法
使用方法はドキュメントコメントを見れば問題ないはず
キャンセルなど特になにもしない場合は {} を渡す
let ok :Void -> Void = {
print("OK")
}
Alert.show(
title: "title",
withMsg: "msg",
okAction: ok,
cancalAction: {})