LoginSignup
7
5

More than 5 years have passed since last update.

UIViewでAlertを出す方法(ViewController非経由?)

Last updated at Posted at 2016-02-09

タイトル、非経由だと語弊がありそうですけど以下の事情です


UIView上でアラートを出そうとした際に、iOS8以降での仕様変更のおかげさまでUIAlertViewが非推薦になり、ViewControllerを経由しなければならなくなりました

ただViewを別で作ってViewControllerで表示させていたり、NibでつくったUIViewの上にまたUIViewを載せていたりするとViewControllerに到達するのが非常にめんどくさく、なんとかアラートを発火させるView上でアラートを表示できないものかと思い探してたら以下の方法が見つかりました

まずは非推薦の方法

UIAlertView(title: "Missing Text", message: "テキストを入力してください。", delegate: nil, cancelButtonTitle: "OK").show()

なんて簡単・・・ただしこれでは黄色い三角がでかでかとで続けてしまいます

ViewControllerを取得して実装する方法


let alertController = UIAlertController(title: "Missing!", message: "テキストを入力してください。", preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(OKAction)

var baseView = UIApplication.sharedApplication().keyWindow?.rootViewController
while ((baseView?.presentedViewController) != nil)  {
  baseView = baseView?.presentedViewController
}

baseView?.presentViewController(alertController, animated: true, completion: nil)

ここではそのViewが載っているViewControllerを取得してそいつのpresentViewControllerメソッドを使っています
whileのとこの仕組みは調査中です・・・

参考: http://swift-salaryman.com/topmost.php

7
5
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
7
5