使用didSelectRowAtIndexPath缩回表格视图单元格

时间:2011-04-06 19:08:46

标签: iphone objective-c ios uitableview

我正在尝试制作一个可以单击的单元格的表格,然后变大以显示所有信息。到目前为止,这使用以下代码

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Note: Some operations like calling [tableView cellForRowAtIndexPath:indexPath]
    // will call heightForRow and thus create a stack overflow
    if(selectedCellIndexPath != nil
       && [selectedCellIndexPath compare:indexPath] == NSOrderedSame){
    labelSize = [[items objectAtIndex:indexPath.row] sizeWithFont:[UIFont fontWithName:@"Helvetica" size:13.0] 
                         constrainedToSize:CGSizeMake(220.0f, MAXFLOAT) 
                             lineBreakMode:UILineBreakModeWordWrap];
    return labelSize.height + 40;
    }
    return 68;
}

这样可以正常工作并使细胞更大。但是没有办法关闭细胞。我试过读取,在这种情况下是labelSize.heigth,但这与点击的单元格的实际高度不对应。

有人知道关闭细胞的好方法,换句话说。当第二次敲击单元格时,需要将高度设置为68。

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以检查selectedCellIndexPath实例变量。

如果您想要多重选择,请执行以下操作:

NSMutableSet *_selectedIndexPaths;

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 68.0f;

    if ([_selectedIndexPaths containsObject:indexPath]) {
        height *= 2.0f;
    }

    return height;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_selectedIndexPaths containsObject:indexPath]) {
        [_selectedIndexPaths removeObject:indexPath];
    } else {
        [_selectedIndexPaths addObject:indexPath];
    }

    [UIView animateWithDuration:0.35 
                          delay:0.0 
                        options:UIViewAnimationOptionLayoutSubviews
                     animations:^{
                         [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];                         
                     }
                     completion:NULL];
}

答案 1 :(得分:0)

我会对Phil Larson的回答发表评论,但评论中的多行代码效果不佳。

过去,至少,Apple建议使用空的beginUpdates / endUpdates块来调整动画细胞的大小。这是我第一次看到UIView动画用来达到同样的效果。我在自己的代码中使用了这种技术。从Phil的代码中,我将[UIView animateWithDuration...替换为以下

[tableView beginUpdates];
[tableView endUpdate];

如果我错了并且有新建议使用UIView动画,我很想看到它的讨论。我不会想到采用这种方法。

相关问题