I was researching various things to make an app without using Storyboard
, but the navigation bar did not work even if I copied the code on the net.
I hope it helps people who are in the same situation as me, and I will put a solution.
First, add the code to SceneDelegate.swift
.
SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
//By default_So rewrite it as a scene
guard let scene = (scene as? UIWindowScene) else { return }
//firstViewController is the first screen displayed(rootViewController)
let firstViewController = ViewController()
let navigationController = UINavigationController(rootViewController: firstViewController)
window = UIWindow(windowScene: scene)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
}
window
has moved from AppDelegate
toSceneDelegate
in the iOS 13 update, and even if you search, most of the information is adding code to AppDelegate
.
I think you can think of it as "I used to implement it with AppDelegate
, but now I need to describe it in SceneDelegate
".
Next, we'll write the code that implements the navigation bar.
ViewController.swift
class ViewController: UIViewController {
var button: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = "First"
button = UIBarButtonItem(barButtonSystemItem: .fastForward, target: self, action: #selector(click))
navigationItem.rightBarButtonItem = button
}
@objc func click() {
let second = SecondViewController()
navigationController?.pushViewController(second, animated: true)
}
}
SecondViewController.swift
class SecondViewController: UIViewController {
var button: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
title = "Second"
view.backgroundColor = .systemTeal
button = UIBarButtonItem(barButtonSystemItem: .fastForward, target: self, action: #selector(click))
navigationItem.rightBarButtonItem = button
}
@objc func click() {
let third = ThirdViewController()
navigationController?.pushViewController(third, animated: true)
}
}
ThirdViewController.swift
class ThirdViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Third"
view.backgroundColor = .purple
}
}
I tried to put the transition movement twice to give a feeling of movement.
By the way, this article is intended to implement a navigation bar, so I won't cover UIWindow
or @ objc
.
** It looks like this when you actually move it **
Recommended Posts