ios - UITableView indexPath 部分逻辑

标签 ios uitableview nsindexpath

这是我的 cellForRowAtIndexPath UITableView 委托(delegate)方法的简化代码:

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"blahblahblah"];
if (cell == nil) {
    // No cell to reuse => create a new one
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"blahblahblah"] autorelease];
}
cell.textLabel.text = @"";
cell.detailTextLabel.text = @"";
cell.backgroundView = NULL; //problem here

// Initialize cell
//blah blah blah
//now to the good part...

if(indexPath.section == 1) {
    cell.backgroundView = deleteButton;
    cell.userInteractionEnabled = YES;
    cell.textLabel.text = nil;
    cell.detailTextLabel.text = nil;
}

else if(indexPath.section == 0) {
    NSLog(@"section: %i row: %i", indexPath.section, indexPath.row);
    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"foobar";
            //more stuff
            break;

        //lots more cases

        default:
            break;
    }
}

return cell;

我的问题是第 1 节中的第一个单元格(第 0 节有 10 个单元格,第 1 节只有 1 个单元格)分配的信息仅应分配给第一个部分的单元格 0。因此,它不是获取 deleteButton 背景等,而是获取标签标题“foobar”。我不太确定为什么会这样,因为我的 if 语句非常清楚。有什么想法吗?

编辑:将 backgroundView 设置为 NULL 会导致那些带有文本的单元格在离开 View 时返回时没有任何背景。所以这不是一个可行的解决方案。此外,detailTextLabel 的文本仍然设置在不应包含任何文本的单元格上。

这就是它的样子,单元格 backgroundViews 设置为 nil,文本显示在删除单元格上不应该出现的地方:

enter image description here

解决方案,如 Alex Deem 所推荐(用此代码替换旧的出队代码):

NSString* identifier;
if(indexPath.section == 0)
    identifier = @"0";
else
    identifier = @"1";
UISwitch *switchView;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
    // No cell to reuse => create a new one
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier] autorelease];

最佳答案

您应该阅读有关细胞重用的文档。

您应该为这两个部分中的每一个使用不同的 reuseIdentifier,因为它们是具有根本不同样式的单元格。

关于ios - UITableView indexPath 部分逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8351286/

相关文章:

ios - 尝试将 iCarousel 实现到我的项目中,但没有显示任何内容 - 我做错了什么?

ios - 如何为自动调整单元格正确设置自动布局约束

ios - 带有 UIBarPositionTopAttached 的 UISearchController 将 UISearchBar 抛出屏幕;不可能有标准的 UISearchController 和 UITableView?

iOS - 检查选择了哪个 UITabBar 选项的简单方法

ios - UITableView 单元格在高度变化后显示错误的内容

ios - @2x 图像的低分辨率

ios - 大于等于的 NSPredicate 问题

ios - 验证用户输入的数字

ios - 从 UITableView 中删除自定义行

uitableview - 如何单击按钮将 tableview 单元格附件类型重置为无?