1
我試圖在按鈕從ViewController1切換到ViewController2時更改根視圖控制器,反之亦然。問題是我設置我的第二個視圖控制器作爲根視圖控制器後,我越來越黑屏。我附上我的代碼。iOS - 在更改根視圖控制器時獲取黑色視圖
我AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyBoard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc1 = storyBoard.instantiateViewControllerWithIdentifier("VC1") as! VC1
let nc = UINavigationController(rootViewController: vc1)
self.window?.rootViewController = nc
self.window?.makeKeyAndVisible()
return true
}
第一個視圖控制器(VC1.swift)
class VC1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
deinit {
print("Deinit of VC1")
}
@IBAction func btnTapped(sender: AnyObject) {
let window = UIApplication.sharedApplication().windows[0]
let rootNavigationControl = window.rootViewController as! UINavigationController
let storyBoard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc2 = storyBoard.instantiateViewControllerWithIdentifier("VC2") as! VC2
let nc = UINavigationController(rootViewController: vc2)
rootNavigationControl.presentViewController(nc, animated: true) {() -> Void in
// ------- Becomes black screen here ----------
rootNavigationControl.viewControllers = [vc2]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
第二個視圖控制器(VC2.swift)
class VC2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
deinit {
print("Deinit of VC2")
}
@IBAction func btnTapped(sender: AnyObject) {
let window = UIApplication.sharedApplication().windows[0]
let rootNavigationControl = window.rootViewController as! UINavigationController
let storyBoard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc1 = storyBoard.instantiateViewControllerWithIdentifier("VC1") as! VC1
let nc = UINavigationController(rootViewController: vc1)
rootNavigationControl.presentViewController(nc, animated: true) {() -> Void in
rootNavigationControl.viewControllers = [vc1]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
請能有人幫助我找出問題所在。 在此先感謝您的幫助。
雖然我同意在推動VC2導航控制器的堆棧更爲常見在iOS和可能更好的UX中,iOSFresher明確要求用VC2將VC1 **替換爲**。不是VC2被推入堆棧。 –
如果你真的想替換視圖控制器,我會用 self.navigationController?.setViewControllers([vc2],animated:true)來代替self.navigationController?.pushViewController(vc2,animated:true) –