2010-01-18 35 views
8

有誰知道一個簡單的方法來管理一個viewController中的幾個tableViews? 這裏是我如何在做它至今:如何在1個viewController中管理2個tableviews?

-(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) 
... 
} 

我發現它真的很煩人,我要使用if/else語句爲每一個委託方法。另外,當有很多tableViews時,真的很難閱讀。此外,我有NSURLConnection相同的問題,等等......只要我有幾個對象響應相同的委託協議,事情變得混亂。

什麼是使事情變得更簡單的最好方法? 謝謝

回答

6

您可以使用選擇器和表視圖的某種標識符(例如UIView標記)。類似這樣的:

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

當然,您需要爲每個表視圖都有一個方法。假設你的兩個表有一個標籤100和101,你將有tableView100:titleForHeaderInSectiontableView101:titleForHeaderInSection

+0

這很方便!謝謝。 – nmondollot 2010-01-19 16:12:52

6

我經常用到的一種方法實際上是讓兩個UITableView的代表和數據源是不同的對象。這樣,你的視圖控制器就不必來回切換,而且你的代碼總體上更乾淨簡單。

+0

這很有道理。下次我必須處理幾個委託對象。謝謝。 – nmondollot 2010-01-19 16:11:55

相關問題