LoginSignup
20
23

More than 5 years have passed since last update.

Swiftコードで画面遷移

Posted at

storyboardを使いたくなかったのでコーディング。
遷移の管理はナビゲーションバーを使用する。

AppDelegate.swift
...
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  // トップ画面のコントローラ
  let first = FirstViewController()
  // ナビゲーションバーのコントローラ
  let navi = UINavigationController(rootViewController: first as UIViewController)
  // 今回はスワイプでバックする機能は無効化しておく
  navi.interactivePopGestureRecognizer?.enabled = false

  window = UIWindow(frame: UIScreen.mainScreen().bounds)
  window?.rootViewController = navi
  window?.makeKeyAndVisible()

  return true
}
...
FirstViewController.swift
...
override func viewDidLoad() {
  // ナビゲーションバーの設定
  navigationController?.navigationBar.backgrondColor = UIColor.grayColor()
  navigationController?.setNavigationBarHidden(false, animated: false)
  // 遷移先でナビゲーションバーに戻るボタンを表示させない
  navigationItem.setHidesBackButton(true, animated: false)

  // 次へ進むボタン
  let button = UIButton(frame: CGRectMake(0, 0, view.bounds.width / 2, view.bounds.height / 2))
  button.layer.cornerRadius = 10
  button.layer.position = view.center
  // ボタンを押した(離した)際のイベントを登録
  button.addTarget(self, action: "goSecond:", forControlEvents: .TouchUpInside)
  view.addSubview(button)
}

func goSecond(sender: UIButton) {
  let second = SecondViewController()
  next.modalTransitionStyle = .CrossDissolve
  // 変数に任意の値を渡せる
  next.myMessasge = "トップ画面からの遷移" 
  // 画像データも渡せるので、撮影した画像をアルバムに保存しなくて良い
  next.myImage = UIImage(...)
  // 遷移履歴に追加する形で画面遷移
  navigationController?.pushViewController(second as UIViewController, animated: true)
}
...
SecondViewController.swift
// 省略
ThirdViewController.swift
...
func goFirst(sender: UIButton) {
  let first = FirstViewController()
  top.modalTransitionStyle = .CrossDissolve
  // 遷移履歴は First -> Second -> Third -> First となる
  navigationController?.pushViewController(first as UIViewController, animated: true)
}

func backOne(sender: UIButton) {
  // 遷移履歴を一つ戻る
  // 一度戻ると再び進むことはできないので注意
  navigationController?.popViewControllerAnimated(true)
}

func backTwo(sender: UIButton) {
  // 遷移履歴を二つ戻る
  let count = navigationController!.viewControllers.count - 3
  let target = navigationController!.viewControllers[count]
  target.modalTransitionStyle = .CrossDissolve
  navigationController?.popToViewController(target as UIViewController, animated: true)
}

func backRoot(sender: UIButton) {
  // 遷移履歴の最初に戻る
  navigationController?.popToRootViewControllerAnimated(true)
}
...

ナビゲーションバーを使うとその分画面がずれたりずれなかったり、
調整が面倒なのだがそれはまた別の話。

20
23
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
20
23