How to manage 2 tableviews in 1 viewController?

帅比萌擦擦* 提交于 2019-12-30 08:32:35

问题


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 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.



来源:https://stackoverflow.com/questions/2086974/how-to-manage-2-tableviews-in-1-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!