iOS 7 beginUpdates endUpdates不一致

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

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

我有一个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];

}

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

解决方法

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

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

>编写一个始终返回NSIndexPath实例并使用它生成键的方法:

- (NSIndexPath *)keyForIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath class] == [NSIndexPath class]) {
        return indexPath;
    }
    return [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
}

>按数据识别行,而不是索引路径.例如,如果您的数据模型是NSString数组,请使用该字符串作为selectedIndexes映射的键.如果您的数据模型是NSManagedObjects数组,请使用objectID等.

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

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

以上是来客网为你收集整理的iOS 7 beginUpdates endUpdates不一致全部内容,希望文章能够帮你解决iOS 7 beginUpdates endUpdates不一致所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。