Push View Controller - Example


 

Push View Controller - Example

In this pushViewController example, you'll find the way to make transition between two views.

In this pushViewController example, you'll find the way to make transition between two views.

In this pushViewController example, you'll find the way to make transition between two views.

In Cocoa, we have several instance methods which is used for pushing and popping stack items. For example ...
– pushViewController:animated:
– popViewControllerAnimated:
– popToRootViewControllerAnimated:
– popToViewController:animated:


etc... But when we use "pushViewController" we means to show the next top stack item from the stack. The UIViewController automatically adjust the size of next view according to navigation and tab bar in the application..

Syntax of Push View Controller

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated

As you can see that it takes two parameters 1) viewController & 2) animated.

Animated means it'll show a animated transition of view on action, if it has given "YES" otherwise view will be loaded simply without any effect. Whereas viewController is pushed onto the stack and that object neither can be an instance of tab bar controller nor on the navigation stack at launch time.

Example Code: pushViewController

In the example we are going to load the next UIView from Stack using pushViewController. First of all create a navigation based application and uncomment the table view code in viewController.m. Now, create an array(NSMutableArray), define it's property in ViewController.h.

In ViewController.m, synthesize the array and release it. Now you can some items to the array and load it on table view. It is just similar to the UITableView app example. But in this example we wanted to load a view on click.. so here we need a UIView.

You can either add a new UIView or create it programatically in "didSelectRowAtIndexPath". And the code for pushViewController will also be written in the same method.

Code

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//Navigation logic may go here. Create and push another view controller.
UIViewController *myViewController = [[UIViewController alloc] init];
myViewController.title = @"My First View";
myViewController.view.backgroundColor = [UIColor redColor];

//to push the UIView.
[self.navigationController pushViewController:myViewController animated:YES];

}

On Building the application, you'll get following output.


In the next example i will show you how to create a UIView at run time.

Download Code

Ads