【发布时间】:2011-11-14 16:36:10
【问题描述】:
我有一个分段的 tableView,我希望我的用户从表中选择一个项目。当他们选择项目时,项目旁边应该会出现一个检查(使用UITableViewCellAccessoryCheckmark)。如果他们做出了先前的选择,则应从先前选择的行中删除检查。这是我正在使用的代码:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
int newRow = [indexPath row];
int oldRow = [lastIndexPath row];
if (newRow != oldRow || newRow == 0)
{
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
newCell.accessoryType = UITableViewCellAccessoryCheckmark;
UITableViewCell *oldCell = [tableView cellForRowAtIndexPath: lastIndexPath];
oldCell.accessoryType = UITableViewCellAccessoryNone;
[lastIndexPath release];
lastIndexPath = indexPath;
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
lastIndexPath 在.h 文件中私下声明。
此代码适用于未分段的小列表。但是在一个被分割的大表中,它会在其他部分的行中放置随机复选标记。几乎就像cellForRowAtIndexPath 忽略了 indexPath 中的部分。
如果我选择的行数大于最小部分中的行数,代码也会崩溃。
这是 cellForRowAtIndexPath 的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *itemSection = [items objectForKey:key];
static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SectionsTableIdentifier] autorelease];
}
NSArray *rowLabel = [itemSection objectAtIndex:row];
cell.textLabel.text = [rowLabel objectAtIndex:1];
NSString *detText = [rowLabel objectAtIndex:0];
detText = [detText stringByAppendingString:@" $"];
detText = [detText stringByAppendingString:[rowLabel objectAtIndex:2]];
cell.detailTextLabel.text = detText;
return cell;
}
【问题讨论】:
-
需要查看
cellForRowAtIndexPath:的代码。我假设您正在使单元格出列并使用重用标识符(cellForRowAtIndexPath:的默认实现)。如果是这种情况,那么您用于创建单元格的代码将重用带有复选标记的单元格作为模板来创建新单元格。为了解决这个问题,您可以做一些事情:“每次在cellForRowAtIndexPath:中创建一个新单元格”或“保留对每个单元格的引用并绕过对cellForRowAtIndexPath:的调用” -
是的 - 我明白你在说什么,这可以解决随机复选标记的第一个问题,但我认为如果我选择的行大于最小部分的行数。这是 cellForRowAtIndexPath 代码:
-
您将无法将该代码发布到评论中。将其添加到您的原始帖子中
标签: iphone objective-c ios uitableview