我想從UIBarButtonItem打開新的視圖控制器。如何讓UIBarButtonItem打開一個新的視圖控制器swift 3
func readQrCode(_ sender:UIBarButtonItem!) {
print("working")
let vc = self.storyboard?.instantiateViewController(withIdentifier: "QRCodeViewController")
}
我想從UIBarButtonItem打開新的視圖控制器。如何讓UIBarButtonItem打開一個新的視圖控制器swift 3
func readQrCode(_ sender:UIBarButtonItem!) {
print("working")
let vc = self.storyboard?.instantiateViewController(withIdentifier: "QRCodeViewController")
}
兩種可能性。如果你沒有一個導航控制器(我通常做),右括號前添加此行:
self.present(vc, animated:true, completion:nil)
如果你有一個導航控制器添加此相反:
self.navigationController?.pushViewController(vc, animated: true)
編輯: (調試你的導航控制器是否存在)
如果你改變了?到!當你運行它時你會得到一個異常,那麼導航控制器不在那裏。請顯示您定義導航控制器的代碼。我會做在AppDelegate中是這樣的:
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
}
其實你可以去通過故事板,用鼠標右鍵單擊UIBarButtom,拖動到你想的SEGUE發生視圖控制器連接。只要你釋放點擊視圖控制器,一個接口將彈出問你想使用什麼類型的segue。然後,你可以選擇顯示細節。這將允許你創建一個segue而不用輸入任何代碼。
我有導航controller.added你共享的代碼,但仍然沒有打開視圖控制器。 –
如果你改變了?到!當你運行它時你會得到一個異常,那麼導航控制器不在那裏。請顯示您定義導航控制器的代碼。我會這樣做在AppDelegate這樣的: – Mozahler
我沒有定義導航控制器的任何地方 –