カテゴリー
iOS Swift

UINavigationControllerサンプルコード

globalにNavigationControllerを設定するにはSceneDelegate内で設定をします。

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(frame: windowScene.coordinateSpace.bounds)
    window?.windowScene = windowScene
    let navigationController = UINavigationController(rootViewController: SequenceViewController())
    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()
}

別のスクリーンへ遷移するには以下のようにします。

@objc private func goToVC() {
  let targetVC = NextViewController()
  navigationController?.pushViewController(targetVC, animated: true)
}

iOSのスクリーン遷移は、navigationController.viewControllersという配列にUIViewControllerをスタックする形で管理します。試しに、遷移先のviewDidLoad内でviewControllers配列をprintしてみます。その時点で表示されているViewControllerは配列内の一番最後のものだと分かります。

// print(navigationController?.viewControllers)

Optional([<ChordGenius.ViewController: 0x106817200>, <ChordGenius.ChordSelectVC: 0x105f07bd0>])

ひとつ前のViewControllerに戻るには、popViewController()を使います。なお、popToRootViewController()は一番最初のVCに戻る時に使います。

Transitionの挙動を設定するにはCATransitionを使い、navigationControllerに設定します。

@objc private func transitionButtonTapped() {
    let transition = CATransition()
    transition.duration = 0.5
    transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
    transition.type = .fade
    navigationController?.view.layer.add(transition, forKey: nil)
    navigationController?.popToRootViewController(animated: false)
}

個別のviewController内に新しいnavigationControllerインスタンスを作成し、presentすることも出来ます。

@objc private func transitionButtonTapped() {
  let targetVC = BookmarkedViewController()
  let navigationVC = UINavigationController(rootViewController: targetVC)
  navigationVC.modalTransitionStyle = .crossDissolve
  navigationVC.modalPresentationStyle = .fullScreen
  self.present(navigationVC, animated: true)
}

viewDidLoad内でNavigationItemを設定するには以下のようにします。

// some basic examples
title = "Manage Songs"
navigationController?.navigationBar.prefersLargeTitles = true
    self.navigationItem.setRightBarButton(UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped)), animated: true)

余談ですが、UINavigationControllerを設定するとview.safeAreaInsets.topの値が少し大きくなります。