我在我的iPhone应用中使用UITableView,我有一个属于一个组的人的列表。我希望当用户单击一个特定的人(因此选择单元格)时,单元格的高度会增加,以显示用于编辑这个人的属性的几个UI控件。

这可能吗?


当前回答

Swift 4及以上

将以下代码添加到tableview的didselect行委托方法中

tableView.beginUpdates()
tableView.setNeedsLayout()
tableView.endUpdates()

其他回答

我喜欢西蒙·李的回答。我实际上并没有尝试这个方法,但它看起来会改变列表中所有单元格的大小。我只是希望改变一下被窃听的细胞。我有点像西蒙,但有一点不同。这将改变选定单元格时的外观。它确实有动画。只是另一种方法。

创建一个int来保存当前选定单元格索引的值:

int currentSelection;

然后:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int row = [indexPath row];
    selectedNumber = row;
    [tableView beginUpdates];
    [tableView endUpdates];
}

然后:

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

    if ([indexPath row] == currentSelection) {
        return  80;
    }
    else return 40;


}

我相信您可以在tableView:cellForRowAtIndexPath:中进行类似的更改,以更改单元格的类型,甚至为单元格加载xib文件。

像这样,currentSelection将从0开始。如果您不希望列表的第一个单元格(在索引0处)默认情况下看起来是选中的,则需要进行调整。

获取所选行的indexpath。重新加载表。在UITableViewDelegate的highightforrowatindexpath方法中,将所选行的高度设置为不同的高度,对于其他的则返回正常的行高度

下面是Simons对Swift 3的简短回答。还允许切换单元格的选择

var cellIsSelected: IndexPath?


  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    cellIsSelected = cellIsSelected == indexPath ? nil : indexPath
    tableView.beginUpdates()
    tableView.endUpdates()
  }


  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if cellIsSelected == indexPath {
      return 250
    }
    return 65
  }

Swift 4及以上

将以下代码添加到tableview的didselect行委托方法中

tableView.beginUpdates()
tableView.setNeedsLayout()
tableView.endUpdates()

reloadData不好,因为没有动画…

这是我目前正在尝试的:

NSArray* paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];

它几乎是正确的。几乎。我正在增加单元格的高度,当单元格被替换时,有时在表格视图中会有一点“小问题”,就像在表格视图中保留了一些滚动位置一样,新单元格(表中的第一个单元格)的偏移量过高,而滚动视图会反弹以重新定位它。