iOS 7 beginUpdates endUpdates不一致

cod*_*der 8 objective-c uitableview nsindexpath ios ios7

编辑:此答案的解决方案与iOS7有时返回有关NSIndexPath,其他时间返回NSMutableIndexPath.这个问题并没有真正关联begin/endUpdates,但希望解决方案能够帮助其他人.


全部 - 我在iOS 7上运行我的应用程序,我遇到了问题beginUpdatesendUpdates方法UITableView.

我有一个tableview,需要在触摸时更改单元格的高度.以下是我的代码:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

        // If our cell is selected, return double height
        if([self cellIsSelected:indexPath]) {
            return 117;
        }

        // Cell isn't selected so return single height
        return 58;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

        ChecklistItemCell *cell = (ChecklistItemCell *)[self.tableview cellForRowAtIndexPath:indexPath];
        [cell.decreaseButton setHidden:NO];
        [cell.increaseButton setHidden:NO];

        // Toggle 'selected' state
        BOOL isSelected = ![self cellIsSelected:indexPath];

        DLog(@"%@", selectedIndexes);

        DLog(@"is selected: %@", isSelected ? @"yes":@"no");
        // Store cell 'selected' state keyed on indexPath
        NSNumber *selectedIndex = @(isSelected);
        selectedIndexes[indexPath] = selectedIndex;

        [tableView beginUpdates];
        [tableView endUpdates];

}
Run Code Online (Sandbox Code Playgroud)

beginUpdatesendUpdates方法是相当不一致的工作.didSelectRowAtIndexPath每次触摸时都会正确调用该方法(我认为UI首先被阻止),并selectedIndexes正确存储交替值.问题是,有时我触摸表格单元格并且所有方法都被正确调用,但单元格高度不会改变.有谁知道发生了什么?

Tim*_*ose 21

iOS7中的行为发生了变化,其中索引路径有时是实例NSIndexPath和其他时间UIMutableIndexPath.问题是isEqual这两个类之间总会返回NO.因此,您无法可靠地将索引路径用作字典键或依赖于其他方案isEqual.

我可以想到几个可行的解决方案:

  1. 编写一个始终返回实例的方法NSIndexPath并使用它来生成密钥:

    - (NSIndexPath *)keyForIndexPath:(NSIndexPath *)indexPath
    {
        if ([indexPath class] == [NSIndexPath class]) {
            return indexPath;
        }
        return [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 按数据标识行,而不是索引路径.例如,如果您的数据模型是数组NSString,请使用该字符串作为selectedIndexes地图的键.如果您的数据模型是数组NSManagedObjects,请使用objectID等.

我在我的代码中成功使用了这两种解决方案.

编辑修改后的解决方案(1)基于@ rob建议返回NSIndexPaths而不是NSStrings.

  • 我通过制作一个"严格"的indexPath并在"forKey"查找中使用它来应用此解决方案.例如:NSIndexPath*strictIndexPath = [NSIndexPath indexPathForItem:indexPath.row inSection:indexPath.section]; (2认同)