简体   繁体   中英

How to get UIBarButtonItem to open a new view controller swift 3

I want to open new view controller from UIBarButtonItem.

func readQrCode(_ sender:UIBarButtonItem!) {
            print("working")
            let vc = self.storyboard?.instantiateViewController(withIdentifier: "QRCodeViewController")
        }

You could actually go through the storyboard, right-click the UIBarButtom, dragging its connection to the view controller you want to make the segue happen. As soon as you release the click on the view controller, an interface is going to pop up asking what type of segue you would like to use. Then, you could choose show detail. That would allow you to create a segue without typing any code.

two possibilities. If you don't have a navigation controller (I usually do), add this line right before the closing brace:

self.present(vc, animated:true, completion:nil)

If you have a navigation controller add this instead:

self.navigationController?.pushViewController(vc, animated: true)

Edit: (to debug whether your navigation controller is there)

if you change the ? to a ! and you get an exception when you run it, then the navigation controller isn't there. please show the code where you defined the navigation controller. I would do it in the AppDelegate like this:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let startupVC = SomeViewController()
        self.window! = UIWindow(frame: UIScreen.main.bounds)
        let mainNavConn = UINavigationController(rootViewController: startupVC)
        self.window!.rootViewController = mainNavConn
        self.window!.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.5, alpha: 1.0)
        self.window!.makeKeyAndVisible()
        return true
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM