iOS:两个tableview的tableview委托方法

7

我有一个类中的表格视图委托方法:

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

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

return [array1 count];
}

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


static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ; 
}

cell.textLabel.text = [array1 objectAtIndex:indexPath.row];

return cell;
}

如果我只有一个UITableView,那还好,但如果我有两个UITableView怎么办?我该如何组织我的代码?使用标签吗?

4个回答

13

看到所有的委托方法都包含tableView:(UITableView *)tableView吗?

你可以在头文件中定义你的表视图,然后只需要简单地写:myTable(假设你的表名为myTable)。

if (tableView == myTable)

那么您可以拥有任意数量的表视图。

例如:

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

return [array1 count];
}

转变成:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == myTable)
    {
       return [array1 count];
    }
    if (tableView == myTable2)
    {
       return [array2 count];
    }

    return 0;
}

3

我的建议是让您的数据源充当表视图的代理,而不是控制器。

这种设计更接近于模型-视图-控制器模式,将允许您拥有更多的灵活性,并避免在代理方法中检查tableView参数具有的特定值。

在您的情况下,您的代理/数据源将是一个类,其成员类型为NSArray,并且实现了UITableViewDelegate协议。


1

可以使用标签来实现。给你的UITableView分别设置标签1和2。

设置一个开关:

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

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ; 
}

switch ([tableView tag]) {
  case 1:{
    [[cell textLabel] setText:@"First tag"]
    break;
  }
  case 2:{
    [[cell textLabel] setText:@"Second tag"]
    break;
  }
  default:
    break;
}

return cell;
}

标签使用得很好,处理多个表格更加容易。 - Vincent

0
每个方法都传递了调用它的表视图的引用。我通常在界面构建器中将每个表格连接到一个输出口,并根据与委托方法和输出口名称中的tableView进行比较,有条件地返回数据源。使用标签也是可能的,但更加混乱,并且在编辑视图结构时更容易出现问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接