LoginSignup
4
2

More than 5 years have passed since last update.

【Xcode 10, swift 4】 UIAlertController を表示してからsegueで画面遷移するサンプル

Last updated at Posted at 2018-09-20

【Xcode 10, swift 4】 UIAlertController を表示してからsegueで画面遷移するコードを書きましたが、エラーメッセージが出て、しばらくつまずきました。

下図のButtonを押すと・・・
Button.gif
以下のようなalertを表示して、キャンセルなら何もしない、OKなら次の画面に遷移するというコードを書きました。Buttonは"myButton"、segue identifierは"toSecondView"としています。
alert.gif

import UIKit

class ViewController: UIViewController {

    @IBOutlet var myButton:UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func myActionSegue(){
        let titleString = "画面遷移"
        let messageString = "画面遷移しますか?"
        let alert: UIAlertController = UIAlertController(title:titleString,message: messageString,preferredStyle: UIAlertController.Style.alert)
        let okAction: UIAlertAction = UIAlertAction(title: "OK",style: UIAlertAction.Style.default,handler:{(action:UIAlertAction!) -> Void in
            self.performSegue(withIdentifier: "toSecondView", sender: true)
        })
        let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル",style: UIAlertAction.Style.cancel,handler:{(action:UIAlertAction!) -> Void in
        })
        alert.addAction(okAction)
        alert.addAction(cancelAction)
        self.view?.window?.rootViewController?.present(alert, animated: true, completion: nil)
    }
}

画面遷移自体はうまく行きましたが、コンソールに以下のようなエラーメッセージが表示されました。
pushViewController:animated: called on <・・・> while an existing transition or presentation is occurring; the navigation stack will not be updated.
しばらく悩みましたが、原因が分かりましたので提示します。

当初、以下の図のように、storyboardでフィールド上の「Button」を右クリックしてsecondViewにpushしていました。これがエラーメッセージの原因でした。
wrongSample.gif
以下の図のように、画面上部の黄色い印を右クリック(矢印)してsecondViewにpushした所、エラーメッセージが消えました。
goodSample.gif
以上、皆様のご参考になるかと思い、提示させて頂きました。

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