LoginSignup
3
0

More than 1 year has passed since last update.

【Swift】iPadデバイスでActionSheetを利用する

Last updated at Posted at 2019-06-26

はじめに

今回Swiftでアクションシートを使ったアプリを作ったのですが、iPadでビルドするとクラッシュしてしまう問題が発生したので解決方法を書いておきます。

エラーの内容

ViewController.swift
 @IBAction func pushButton () {
        let alert = UIAlertController(title: "お腹すいた?", message: nil, preferredStyle: .actionSheet)
        let yesAction = UIAlertAction(title: "うん", style: .default, handler: nil)
        let aLittleBitAcion = UIAlertAction(title: "ちょっと", style: .default, handler: nil)
        let noAction = UIAlertAction(title: "全然", style: .default, handler: nil)
        
        alert.addAction(yesAction)
        alert.addAction(aLittleBitAcion)
        alert.addAction(noAction)
        
        self.present(alert, animated: true, completion: nil)

ボタンを押したときにアラートが表示されるサンプルを作成しました。このときiOSデバイスでビルドしてもクラッシュしませんがiPadでビルドするとhread 1: signal SIGABRTと怒られ、デバッグエリアを見てみるとreason: 'Your application has presented a UIAlertController ~~~となってます。

解決策

alertプロパティにpopoverPresentationController?.sourceView = self.view
と指定してあげるとクラッシュしませんでした。

ViewCntroller.swift
 @IBAction func pushButton () {
        let alert = UIAlertController(title: "お腹すいた?", message: nil, preferredStyle: .actionSheet)
        let yesAction = UIAlertAction(title: "うん", style: .default, handler: nil)
        let aLittleBitAcion = UIAlertAction(title: "ちょっと", style: .default, handler: nil)
        let noAction = UIAlertAction(title: "全然", style: .default, handler: nil)
        
        alert.addAction(yesAction)
        alert.addAction(aLittleBitAcion)
        alert.addAction(noAction)
        
        //ここにぶちこむ
        alert.popoverPresentationController?.sourceView = self.view
        
        self.present(alert, animated: true, completion: nil)

終わりに

今回こちらの記事を参照させていただきました。
アラートのポップアップを下に指定したい場合は上記リンクをご参照下さい。

3
0
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
3
0