LoginSignup
3
2

More than 3 years have passed since last update.

コードで画面遷移 swift

Last updated at Posted at 2021-05-10

■何故コードで画面遷移するのか?

■画面が多い場合
Main.Storyboard上で画面遷移すると蜘蛛の巣上に遷移同士の線が重なってしまうため
見にくい

■ログイン画面があるアプリ
ログインした事がある場合とない場合で始まりの画面が違う
ない場合はログイン画面でIDやパスワードを打つ画面を表示する必要がある。
ある場合ログイン画面を飛ばして最初の画面を表示しなければならない。
こういった条件をコードで書く。

Main.Storyboardは基本使わない。

■Main.Storyboardを消す。

まず初めに
そのまま消すとエラーになる。

この記事通りにするとエラー消えます!
めちゃわかりやすく載ってます!
https://qiita.com/sakiyamaK/items/cf95112a28e84b4c6dff

■1

準備
今時は1つのStoryboardに1つのViewControllerが基本なので

FistViewControllerとFist.Storyboard用意 紐づける
SecondeViewControllerとSeconde.Storyboard用意 紐づける

互いのStoryboardにする事
■UIView用意
■is initial View Controllerにチェック

First.StoryboardにButtonを設置

2

新たにRouter.swiftを用意
初めの画面を用意するshowRootメソッドを準備する。

import UIKit

class Router {

   static  func showRouter(window:UIWindow?) {
        let vc = UIStoryboard.init(name: "First", bundle: nil).instantiateInitialViewController() as! FirstViewController
        let nav = UINavigationController(rootViewController: vc)
        window?.rootViewController = nav
        window?.makeKeyAndVisible()
    }
}

3

AppDelegate.swiftにて先ほどのshowRouterメソッドを呼び出す。

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        let window = UIWindow(frame: UIScreen.main.bounds)
        self.window = window
        Router.showRoot(window: window)
        return true
    }
}

ここまでで最初の画面は表示できている。
次にbuttonを押して画面遷移をしていくコードを書く

4

Router.swiftに下記コードを足していく!

    static func showSeconde(from: UIViewController) {
        let vc = UIStoryboard.init(name: "Seconde", bundle: nil).instantiateInitialViewController() as! SecondeViewController
        show(from: from, next: vc)
    }

//実際に画面遷移するコード  
//NavigationControllerならば横からスライド方式で遷移
//そうでなければModalで遷移下から画面が出てくる。
  static func show(from: UIViewController, next: UIViewController) {
        if let nav = from.navigationController {
            nav.pushViewController(next, animated: true)
        } else {
            from.present(next, animated: true, completion: nil)
        }
    }

5

FistViewController

import UIKit

class FirstViewController: UIViewController {

  //ボタンを紐づけてボタンを押したらshowSwcondeメソッドを呼ぶ
    @IBAction func nextButton(_ sender: Any) {
        Router.showSeconde(from: self)
    }
}

これでコードで画面遷移が行えます。

コードで画面遷移gif.gif

以上です。
これを基本にアプリ作成を行なっていった方が良さそうです!!

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