adding a UITableView programmatically to a UIViewController

前端 未结 5 1317
栀梦
栀梦 2021-02-02 17:37

I\'m loading a UIViewController into one of my Nav controller\'s hierarchies, which will contain some text and some images. At the bottom, I will want to create a expandable and

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 18:03

    Just remember that a UITableViewController is a subclass of UIViewController only with the tableview set as the controller's view.

    So yes definitely possible and used quite frequently when you want to have a tableview but also other custom UI elements which prevent you from using the UITableViewController.

    I'd normally choose to add it to my view controller's view in either its initialisation method or viewDidLoad method. This will vary based on whether you're creating your views from a NIB or entirely programatically.

    In case of NIBs:

    - (id)initWithNibName:(NSString*)nibName bundle:(NSBundle*)bundleName
    {
       if ((self = [super initWitNibName:nibName bundle:bundleName]))
       {
           self.theTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewWhateverStyleYouWantHere];
           theTableView.dataSource = self, theTableView.delegate = self;
           [self.view addSubview:theTableView];
           [theTableView release];
       }
    }
    

    And then you can set the frame of your tableview in your viewDidLoad method.

    I'd personally prefer to do the whole thing in interface builder as you'd achieve the same result with way less code to maintain.

提交回复
热议问题