10
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】NavigationControllerへの画面遷移で値を渡す

Last updated at Posted at 2019-02-21

概要

あるViewControllerから、NavigationControllerの階層下にある次の画面へShowで遷移する際に値を渡す方法です。

ここで、現在のViewControllerはNavigationControllerの階層下にはなく、値の渡し先はNavigationControllerのroot view controllerであるという前提です。

準備

storyboardでNavigationControllerにIdentifierをつけてください。

今回は例のため"NavigationController"としました。

スクリーンショット 2019-02-21 15.05.07.png

値渡し

.swift
let storyboard: UIStoryboard = self.storyboard!
let nc: UINavigationController = storyboard.instantiateViewController(withIdentifier: "NavigationController") as! UINavigationController
let followingVC = nc.viewControllers[0] as! FollowingViewController
followingVC.variable = self.variable  //ここで値渡し

self.present(nc, animated: true, completion: nil)  //画面遷移

ちなみに、nc.viewControllers[0]の部分はnc.topViewControllerでも大丈夫だと思います。(root view controllerを指定するという点においては前者の方が分かりやすくていいですが)

10
15
6

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
10
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?