这是我的 cellForRowAtIndexPath UITableView 委托方法的删节代码:
- (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 会导致那些带有文本的单元格在离开视图时返回没有任何背景。所以这不是一个可行的解决方案。此外,detailTextLabel 的文本仍设置在不应包含任何文本的单元格上。
这是它的外观,单元格 backgroundViews 设置为 nil 并且文本显示在不应该删除的单元格上:
解决方案,由 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];