Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift window.rootViewController vs presentViewController

What is the best practice to switch between multiple views; change the rootViewController or use modal views?

Setting the rootviewController:

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var vc : UIViewController = storyBoard.instantiateViewControllerWithIdentifier("viewTarget") as TargetViewController
var window :UIWindow = UIApplication.sharedApplication().keyWindow!
window.rootViewController = vc;
window.makeKeyAndVisible()

Changing the modal view:

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initViewController: UIViewController = storyBoard.instantiateViewControllerWithIdentifier("viewTarget") as TargetViewController
self.presentViewController(initViewController,animated: false, nil)

I'm confused as to which to use when I need to present the user some other view.

p.s. In my case, I've an app starting with the login form as the rootViewController. After login, I think it's best to change the rootViewController but am I right?

like image 780
user2718075 Avatar asked Jul 01 '15 14:07

user2718075


2 Answers

My suggestion is instead of bothering lot about it you just got to override the rootviewController rest of the thing is taken care by your app.

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let initViewController: UIViewController = storyBoard.instantiateViewControllerWithIdentifier("viewTarget") as TargetViewController
    self.window?.rootViewController? = initViewController

In this code we are just overriding rootview controller from AppDelegate.

like image 95
Shailesh Chandavar Avatar answered Sep 19 '22 11:09

Shailesh Chandavar


The point of the "rootViewController" is to a a central pivot for all of your views.

See it as a the top-most link in series of chains. e.g. views on the left, can talk to views on the right can talk to views in the middle thanks to the "rootViewController". the "common link".. On top of that, it controls (or has the capability of controlling) how the hypothetical views on the left, right and middle are configured etc...

Fine, I worded it a bit trivially, but the (UINavigationController) is specifically for hierarchal content i.e. a UITabViewController is a great example..

I've just noticed a great post on here (Changing root view controller of a iOS Window) whilst finding a decent image to explain it decently.

Kudos to Matt on that post :) Hope this helps.

If not feel free to ask away :)

edit and for reference for others, here's something cheap and quick I slapped together that might get your head wrapped around storyboards :)

https://dl.dropboxusercontent.com/u/61211034/viewFun.zip

Cheers,

A

like image 26
Adrian Sluyters Avatar answered Sep 18 '22 11:09

Adrian Sluyters