Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage 2 tableviews in 1 viewController?

Does anyone know a simple way to manage several tableViews in one viewController? Here is how I've been doing it so far:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
if(tableView == self.tableView1) 
return 1;
else if(tableView == self.tableView2) 
return 2;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(tableView == self.tableView1) 
return @"bla";
else if(tableView == self.tableView2) 
return @"blabla";
}

-(NSString *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == self.tableView1) 
...
else if(tableView == self.tableView2) 
...
}

I find it really annoying that I have to use an if/else statement for EVERY SINGLE delegate method. Plus, it is really hard to read when there are many tableViews. Besides, I have the same problem with NSURLConnection, etc... As soon as I have several objects that respond to the same delegate protocol, things get messy.

What is the best way to make things simpler? Thanks

like image 505
nmondollot Avatar asked Jan 18 '10 15:01

nmondollot


2 Answers

One method which I have often used is to actually have the delegates and data source for the two UITableViews be different objects. This way, your view controller doesn't have to switch back and forth, and your code is overall cleaner and simpler.

like image 188
Grant Paul Avatar answered Oct 13 '22 23:10

Grant Paul


You could use selectors and some kind of identifier for the table views (the UIView tag, for example). Something like this:

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
  return [self performSelector:NSSelectorFromString([NSString stringWithFormat:@"tableView%d:titleForHeaderInSection:", tableView.tag])];
}

Of course you will need to have one method for each of your table views. Suppose your two tables have a the tags 100 and 101, you will have then tableView100:titleForHeaderInSection and tableView101:titleForHeaderInSection.

like image 21
Marco Mustapic Avatar answered Oct 14 '22 00:10

Marco Mustapic