我可以告诉如何在 Objective-C 中做到这一点here,但是我怎样才能将其转换为 swift 呢?
我有一个带有自定义 TableViewCells 的 UITableView,其中有一个名为“expandButton”的 UIButton。我试图弄清楚当单击该单元格的展开按钮时如何更改该特定单元格的高度。
另外,当再次单击时,它应该变回原始大小。
我对 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
}
}
现在,按钮操作方法:
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!
我在这里做错了什么?