2013-08-18 126 views
-1

我有兩個表在同一個類,我需要每個表包含不同的數據,但我有麻煩的委託...如何使每個表包含一個單獨的委託?謝謝,我的英語很抱歉。 。兩個UITableView在同一個類中?數據源和委託

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
    return 1; } 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 

    return [dataTable1 count]; 
    } 

-(UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 


    CeldaFamilia *cell = (CeldaFamilia *)[aTableView dequeueReusableCellWithIdentifier:@"CeldaFamilia"]; 




    if (!cell) { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CeldaFamilia" owner:self options:nil]; 
     cell = [nib objectAtIndex:0]; 

    } 

    cell.propTextFamilia.text =[dataTable1 objectAtIndex:indexPath.row]; 

    return cell; 
    } 
+0

爲什麼這些方法有參數'tableView'有一個特殊的原因。主要原因是你可以做'如果[tableView isEqual:tv1] ...'。 –

回答

3

您可以通過查看按例通過tableView參數做到這一點:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    if (tableView == self.tableView1) { 
     return [dataTable1 count]; 
    } else /* tableView == self.tableView2 */ { 
     return [dataTable2 count]; 
    } 
} 

有了這個模式,你需要把你的所有UITableViewDataSourceUITableViewDelegate方法if語句。

另一種方式來做到這一點是使一個方法,該方法返回表格視圖數據的數組:

- (NSArray *)dataTableForTableView:(UITableView *)tableView { 
    if (tableView == self.tableView1) { 
     return dataTable1; 
    } else /* tableView == self.tableView2 */ { 
     return dataTable2; 
    } 
} 

然後使用該函數在每個數據源/委託方法。例如:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return [[self dataTableForTableView:tableView] count]; 
} 

tableView:cellForRowAtIndexPath:方法可能還需要有一個if聲明,這取決於數據的模樣爲每個表。

但是,我建議你不要使用這兩種模式。如果您爲每個表視圖創建單獨的數據源/委託,您的代碼將更好地組織和更易於理解。您可以使用同一類的兩個實例,也可以創建兩個不同的類並根據需要使用每個類的一個實例。

+0

非常感謝幫助 – Fabio

2

如果您將每個tableView的標籤設置爲不同的數字,您可以使用它來區分它們。

例如,你可以做

tableView1.tag = 1; 
tableView2.tag = 2; 

然後在你的委託和數據源的方法,你可以這樣做:

if (tableView.tag == 1) { 
    //first table data 
} 
else if (tableView.tag == 2) { 
    //second table data 
} 
-1

您可以爲第二個表(secondTable)添加其他類並實現在它的數據源和委託表視圖協議。並在你的視圖控制器,它包含viewDidLoad中的2個表: SecondTable * second = [SecondTable alloc] init]; second.delegate = self; second.datasource = second;

而你的第二個表將是SecondTable類的對象,並且你總是喜歡第一個表。

相關問題