-2

我在视图控制器中有 2 个表视图(表 1,表 2)。我有 2 个数据数组(dataArray1,dataArray2)。我想用相应的数据数组加载表视图,即(table1 = dataArray1,table2 = dataArray2)。我正在尝试下面的代码。但是应用程序崩溃了?这段代码有什么问题?任何帮助,将不胜感激。请不要建议使用 2 个视图控制器。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == self.table1)
        return [dataArray1 count];
    if(tableView == self.table2)
        return [dataArray2 count];
}

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CellIdentifier];
    }
    if(tableView == self.table1)
    {
        cell.textLabel.text =[dataArray1 objectAtIndex:indexPath.row];
    }
    if(tableView == self.table2)
    {
        cell.textLabel.text =[dataArray2 objectAtIndex:indexPath.row];
    }
    return cell;
}
4

2 回答 2

1

为两个表视图提供 2 个不同的单元格标识符

因为两个表格单元格不同,它们应该被重用,为了维护正确重用唯一标识符需要分开

尝试这个

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

    static NSString *CellIdentifier1 = @"Cell1";
    static NSString *CellIdentifier2 = @"Cell2";

    UITableViewCell *cell;

    if(tableView == self.table1)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]
                    initWithStyle:UITableViewCellStyleDefault
                    reuseIdentifier:CellIdentifier1];
        }
        cell.textLabel.text =[dataArray1 objectAtIndex:indexPath.row];

    }
    if(tableView == self.table2)
    {
       cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]
                    initWithStyle:UITableViewCellStyleDefault
                    reuseIdentifier:CellIdentifier2];
        }
        cell.textLabel.text =[dataArray2 objectAtIndex:indexPath.row];
    }
    return cell;
}
于 2013-09-03T08:58:47.733 回答
1

通常你不会在一个视图中创建两个表视图。而是创建一个部分。即使那样,如果您仍然需要两个表格视图,最好使用 View Class 并为它们制作单独的代表。我有一个代码 https://github.com/bishalg/BGRradioList 它向您展示了视图与表格视图的使用。希望对您有所帮助。

于 2013-09-03T09:07:02.173 回答