2013-08-18 51 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类的对象,并且你总是喜欢第一个表。

相关问题