swiftで画面遷移する方法


swiftで画面遷移し、戻るボタンを押した時に元の画面に遷移させる方法を書きます。

まず、senderを作成し、@IBAction func内で以下のように第一引数を「senderの名前」第二引数を「self」とします

 self.performSegue(withIdentifier: "goToResult", sender: self)

その後遷移先の変数に元の画面の変数を送るためにprepareという関数を使用します
以下のようにsegueがgoToResultの時にdestinationVCという変数を作成し、遷移後の変数(ここでいうresultやtipなど)に値を代入します。

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToResult"{
            let destinationVC = segue.destination as! ResultViewController

            destinationVC.result = finalResult
            destinationVC.tip = Int(tip * 100)
            destinationVC.split = numberOfPeople
        }

こうすることで遷移先の画面の変数に値を受け渡せました。
今度は遷移後に元に戻るような関数を作ります。

@IBAction func recalculaterPressed(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }

以上のように@IBAction関数内でself.dismiss(animated:true, completion:nil)とすることで遷移後の画面が消え元の画面に戻ります。