How can I switch views programmatically in a view controller? (Xcode, iPhone)
Have been struggling with this for a while, and can never seem to get a direct answer.
Any help is appreciated!
Solution 1:
If you're in a Navigation Controller:
ViewController *viewController = [[ViewController alloc] init];
[self.navigationController pushViewController:viewController animated:YES];
or if you just want to present a new view:
ViewController *viewController = [[ViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
Solution 2:
If you want to present a new view in the same storyboard,
In CurrentViewController.m,
#import "YourViewController.h"
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
YourViewController *viewController = (YourViewController *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self presentViewController:viewController animated:YES completion:nil];
To set identifier to a view controller, Open MainStoryBoard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.
Solution 3:
Swift version:
If you are in a Navigation Controller:
let viewController: ViewController = self.storyboard?.instantiateViewControllerWithIdentifier("VC") as ViewController
self.navigationController?.pushViewController(viewController, animated: true)
Or if you just want to present a new view:
let viewController: ViewController = self.storyboard?.instantiateViewControllerWithIdentifier("VC") as ViewController
self.presentViewController(viewController, animated: true, completion: nil)
Solution 4:
The instantiateViewControllerWithIdentifier
is the Storyboard ID
.
NextViewController *NVC = [self.storyboard instantiateViewControllerWithIdentifier:@"NextViewController"];
[self presentViewController:NVC animated:YES completion:nil];