UITableView:如何在单击button时dynamic更改单元格高度? 迅速

从这里我可以告诉如何在Objective-C中做到这一点 ,但我怎么能把它转换成快捷?

我有一个UITableView自定义TableViewCells有一个名为“expandButton”的UIButton。 我试图找出如何改变该单元格的expandButton单击该特定单元格的高度。

另外,再次点击时,应该变回原来的大小。 我不熟悉ObjectiveC,所以请在Swift中帮助我。 预先感谢一堆!

这是我到目前为止:

//Declaration of variables as suggested var shouldCellBeExpanded:Bool = false var indexOfExpendedCell:NSInteger = -1 

现在在ViewController里面。 注意:TableViewCell是我的自定义单元格的名称。

  //Inside the ViewController func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell:TableViewCell = TableViewCell() { cell.stopWatch = stopWatchBlocks[indexPath.row] cell.expandButton.tag = indexPath.row //Adding action to the expand button cell.expandButton.addTarget(self, action: "expandButtonAction1:", forControlEvents: UIControlEvents.TouchUpInside) return cell } } 

现在,button操作方法:

  func expandButtonAction1(button:UIButton) { button.selected = !button.selected if button.selected { indexOfExpendedCell = button.tag shouldCellBeExpanded = true self.TableView.beginUpdates() self.TableView.reloadRowsAtIndexPaths([NSIndexPath(forItem: indexOfExpendedCell, inSection: 0)], withRowAnimation: .Automatic) self.TableView.endUpdates() button.setTitle("x", forState: UIControlState.Selected) } else if !button.selected { indexOfExpendedCell = button.tag shouldCellBeExpanded = false self.TableView.beginUpdates() self.TableView.reloadRowsAtIndexPaths([NSIndexPath(forItem: indexOfExpendedCell, inSection: 0)], withRowAnimation: .Automatic) self.TableView.endUpdates() button.setTitle("+", forState: UIControlState.Normal) } } 

最后是HeightForRowAtIndexPath

  func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if shouldCellBeExpanded && indexPath.row == indexOfExpendedCell { return 166.0 } else { return 91.0 } } 

我想我错过了一些东西,因为细胞一旦被点击就会膨胀,但是它不会“收缩”回到91!

我在这里做错了什么?

尽量不要使用选定的标签作为切换单元格状态,如此。 一旦select一个单元格,再次点击它将不会取消select。 相反,你可以使用shouldCellBeExpanded标志:

 func expandButtonAction1(button:UIButton) { shouldCellBeExpanded = !shouldCellBeExpanded indexOfExpendedCell = button.tag if shouldCellBeExpanded { self.TableView.beginUpdates() self.TableView.endUpdates() button.setTitle("x", forState: UIControlState.Normal) } else { self.TableView.beginUpdates() self.TableView.endUpdates() button.setTitle("+", forState: UIControlState.Normal) } } 

另外,根据我的经验,reloadRowsAtIndexPath方法是不必要的。 除非需要自定义animation,否则单独使用beginUpdates()和endUpdates()应该可以做到这一点。