LoginSignup
6
4

More than 3 years have passed since last update.

別画面に値を渡す方法について

Posted at

画面遷移時に値を渡す

画面遷移時に遷移先の変数varに値を渡すことで、別の画面に値を渡すことができます。

ViewController
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "second") as! secondViewController
secondViewController. value = "value"
self.present(secondViewController, animated: true, completion: nil)
secondViewController
class secondViewController: UIViewController {

    var value = String()

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

画面遷移時以外で値を渡す

tabBarControllerは、最初にタブを切り替えた時に画面が生成され、削除されないため
画面遷移時以外に値を渡す方法が必要になります。

プロトコルを使用して、特定の処理後に実行させることで、別の画面に値を渡したり処理を行うことができます。

ViewController
var process: anotherScreenProcess!

class ViewController: UIViewController {

     override func viewDidLoad() {
          super.viewDidLoad()

          self.process = secondViewController() as anotherScreenProcess
          self.process.sendValue()
     }
}
secondViewController

protocol anotherScreenProcess {
    func sendValue()
}

class secondViewController: UIViewController, anotherScreenProcess {
     override func viewDidLoad() {
          super.viewDidLoad()
     }

     // 別画面からの処理
     func sendValue() {

     }
}

tabBarControllerについて

tabBarControllerは最初の画面遷移時のみ画面が作成され、削除されません。
そのため、プロトコルの使用以外に作成したtabBarControllerを削除することで、
画面自体の再作成を行うことができます。

self.tabBarController!.viewControllers![1].dismiss(animated: true, completion: nil)
6
4
1

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