Swift screen transition does not work as intended

Asked 1 years ago, Updated 1 years ago, 48 views

I'm writing the code for the screen transition with swift, but it doesn't work.

Feature you are trying to implement: Tap the button placed to the right of navigationbar to push transition.

Result: No error when executed, but no transition when tapped.When you tap, the debug print statement in the function of the button is running, so the button itself seems to be working.

I'm a beginner at Swift, so I'm afraid I'm not good at this code, but I appreciate your cooperation.

// Code for the first screen
import UIKit

classViewController:UIViewController {

    let navBar = UINavigationBar (frame: CGRect (x:0, y:40, width: UISscreen.main.bounds.size.width, height:100))
    let navItem: UINavigationItem=UINavigationItem(title: "Title")

    override func viewDidLoad(){

 super.viewDidLoad()

        view.backgroundColor=UIColor.gray
        navItem.rightBarButtonItem = UIBarButtonItem(title: "Transition", style: UIBarButtonItem.Style.plain, target:self, action:#selector(self.rightHandAction))
        navBar.pushItem(navItem, animated:true)
        self.view.addSubview(navBar)

    // Screen transition function 
    @objc func rightHandAction(_sender:UIBarButtonItem){
        print("right bar button action")
        let vcC —UIViewController=viewControllerConfig()
        let naviVC:UINavigationController=UINavigationController (rootViewController:vcC)
        self.navigationController?pushViewController(naviVC, animated:true)
    }
}

// The code of the transition destination screen
import UIKit

class viewControllerConfig:UIViewController {

    override func viewDidLoad(){
        super.viewDidLoad()
        self.title="Config"
        self.view.backgroundColor=UIColor.cyan
    }

}

swift

2022-09-30 21:48

1 Answers

self.navigationController? is probably because nil.

in rightHandAction()
self.navigationController?pushViewController(naviVC, animated:true)

I think it ended when was unwrapped.

Instead of adding UINavigationBar on your own, you should set the NavigationController correctly based on the reference link below.

Reference Links
Summary of screen transitions on Swift - Qiita


2022-09-30 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.