StuartM
StuartM

Reputation: 6823

Setting up a UITableView inside View Controller Programatically

I have setup a UITableView controller within my view controller as follows:

fieldView = [[UITableView alloc] initWithFrame:CGRectMake(0, logoView.bounds.size.height, 320, (screen.size.height - logoView.bounds.size.height)) style:UITableViewStylePlain];
[fieldView setBackgroundColor:[UIColor greenColor]];
fieldView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin;

The view controller is setup to be a TableViewDelegate as follows:

 UIViewController <UITableViewDelegate, UITableViewDataSource...

Question: What do I need to do to the table view delegate methods for them to control this added sub view?

#pragma mark - 
#pragma Table View Delegate Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSLog(@"Here");
    return 1;
}
- (NSString *)tableView:(UITableView *)fieldView titleForHeaderInSection:(NSInteger)section {
    NSString *sectionName;
    NSLog(@"Here2");

The above methods are in the view controller but not called?

Upvotes: 0

Views: 3412

Answers (2)

nkongara
nkongara

Reputation: 1229

You need to set the delegate & data source for the table view.

fieldView.delegate = controller; // self, if you are creating this table inside your controller

Upvotes: 0

rmaddy
rmaddy

Reputation: 318814

You need:

// Add these right after creating the UITableView
fieldView.delegate = self;
fieldView.dataSource = self;

// don't forget to add the tableview
[self.view addSubview:fieldView];

You also need all of the basic UITableViewDelegate and UITableViewDataSource methods. It's exactly the same as if you had implemented a UITableViewController. At a minimum you need:

tableView:numberOfRowsInSection:
tableView:cellForRowAtIndexPath:

If you plan to support table editing there are additional methods you must implement and override.

Upvotes: 5

Related Questions