我最初尝试这样做,以便为UITableView存储一个UITableViewCell高度(self.cellHeights)的NSMutableDictionary.每次点击UITableViewCell,该单元格将根据存储在该特定indexPath的NSMutableDictionary中的值在两个不同的高度之间展开或缩小:
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber *heightNSNumber = [self.cellHeights objectForKey:indexPath];
if (!heightNSNumber)
{
heightNSNumber = [NSNumber numberWithFloat:100.0];
[self.cellHeights setobject:heightNSNumber forKey:indexPath];
}
return [heightNSNumber floatValue];
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSNumber *heightNSNumber = [self.cellHeights objectForKey:indexPath];
if (!heightNSNumber)
{
heightNSNumber = [NSNumber numberWithFloat:100.0];
[self.cellHeights setobject:heightNSNumber forKey:indexPath];
}
if ([heightNSNumber floatValue] == 100.0)
{
[self.cellHeights setobject:[NSNumber numberWithFloat:50.0]
forKey:indexPath];
} else {
[self.cellHeights setobject:[NSNumber numberWithFloat:100.0]
forKey:indexPath];
}
[tableView beginUpdates];
[tableView endUpdates];
}
由于我不知道的原因,通过[self.cellHeights objectForKey:indexPath]获取单元格的高度在tableView:didSelectRowAtIndexPath:工作正常.但是,尝试获取tableView中的单元格高度:heightForRowAtIndexPath:通过[self.cellHeights objectForKey:indexPath]总是返回nil,因为似乎用于存储高度的indexPath与用于获取单元格高度的indexPath不匹配,即使它们对indexPath.section和indexPath.row具有相同的值.因此,将“相同”索引路径的新对象添加到self.cellHeights中(显而易见,因为self.cellHeights.count此后增加).
当您使用行([NSNumber numberWithInteger:indexPath.row])将单元格高度存储在NSMutableDictionary中时,这不会发生,所以这是我现在在做的,但是我想了解为什么indexPath不工作的关键.
解决方法
只需通过添加以下行重新创建indexPath:
indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
瞧. tableView:heightForRowAtIndexPath:内部使用NSMutableIndexPath实例(就像使用断点看到的那样).不知何故,在计算哈希键时,这些实例似乎与NSIndexPath不协调.
通过将其转换回NSIndexPath,那么一切正常.