问题
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
回答1:
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
.
回答2:
One method which I have often used is to actually have the delegates and data source for the two UITableView
s be different objects. This way, your view controller doesn't have to switch back and forth, and your code is overall cleaner and simpler.
来源:https://stackoverflow.com/questions/2086974/how-to-manage-2-tableviews-in-1-viewcontroller