我有一个UITableView,它在选中一行时显示复选标记。问题是,当我在didSelectRowAtIndexPath中选择一行并在选中的行上添加一个复选标记时,它会添加一个额外的复选标记。这是我的代码
任何帮助都将不胜感激。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text=[[Model.category objectAtIndex:indexPath.row] categoryName];
cell.imageView.image=[[Model.category objectAtIndex:indexPath.row]categoryImage];
//cell.detailTextLabel.text =@"Breve Descripción de la categoria";
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if ([self.tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark) {
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType =UITableViewCellAccessoryNone;
[self.cellSelected removeObject:indexPath];
}else {
[tableView cellForRowAtIndexPath:indexPath].accessoryType=UITableViewCellAccessoryCheckmark;
[self.cellSelected addObject:indexPath];
}
[self checkMark];
[tableView reloadData];
}
- (void)checkMark{
for (NSIndexPath * indexPath in self.cellSelected) {
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType=UITableViewCellAccessoryCheckmark;
}
}发布于 2014-05-19 06:21:52
试试这个:
在.m文件中声明:
@interface MyViewController () {
NSIndexPath *__selectedPath;
}在tableView:cellForRowAtIndexPath:中,检查给定的indexPath是否与ivar中存储的相同:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//configure cell
if ([__selectedPath isEqual:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}在tableView:didSelectRowAtIndexPath中,如果单元格已被取消选择,则存储指向所选NSIndexPath或nil的指针
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
__selectedPath = indexPath;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
__selectedPath = nil;
}
}我在没有签入Xcode的情况下写了它,所以可能会有一些打字错误,但我展示了主要思想。在我看来,你不应该在你的tableView:cellForRowAtIndexPath:方法中调用[self checkMark];。
此外,如果您希望一次只有一个选定的单元格,则不应该创建NSMutableArray来存储NSIndexPath。看起来你的cellSelected一次存储2个NSIndexPaths,这就是为什么你会有这种奇怪的行为。
https://stackoverflow.com/questions/23727255
复制相似问题