Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a UIViewController programmatically?

I am working in a app where i have data in UITableView. It is like a drill down application. User will click on a row and will go to next page showing more records in a UITableView. But problem in my case is that i dont know upto how many level user can drill. The number of levels are not fixed. So now i am thinking to create and add the viewcontrollers programmatically. Is it possible?? if yes how? thanks in advance.

like image 925
pankaj Avatar asked Apr 22 '10 06:04

pankaj


People also ask

What is a UIViewController?

A UIViewController is an object which manages the view hierarchy of the UIKit application. The UIViewController defines the shared behavior and properties for all types of ViewController that are used in the iOS application. The UIViewController class inherits the UIResponder class.

What is the difference between ViewController and UIViewController?

Both are used for different purpose. A UIViewController class manages a ViewContoller which is responsible for actions that happen within that View controller. This class is aware of actions that happen on view controller, like ViewDidLoad, ViewWillApper, ViewDidAppear, ViewWillDisapper, ViewDidDisapper.

How do I push a controller without navigation controller?

You can't push a view controller onto a navigation controller if there is no navigation controller. If you are wanting to be pushing controllers and have it display the topmost controller and everything, just use a UINavigationController and be done with it.


2 Answers

UIViewController *controller = [[UIViewController alloc] init];
controller.view = whateverViewYouHave;

Do you have your own view controller that you coded? In that case you probably don't need to set the view property as it has been set in IB if that is what you used. When you have your controller you can push it onto the navigationController or view it modally etc.

like image 161
willcodejavaforfood Avatar answered Oct 21 '22 23:10

willcodejavaforfood


UIViewControllers are always created programmatically. It sounds like you just need to have the same class for each level of view controller, e.g.:

//CoolViewController:UITableViewController
//CoolViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.isAtTopLevel) {
        CoolViewController *cvc = [[CoolViewController alloc] initWithRecord:[self.records objectAtIndex:indexPath.row]];
        [self.navigationController pushViewController:cvc animated:YES];
        [cvc release];
    } else {
        //do something else
    }
}

In this case, thingies would be some sort of recursive NSArray (i.e. an array of arrays).

like image 32
shosti Avatar answered Oct 22 '22 01:10

shosti