我可以从 here 中知道如何在 objective-c 中执行此操作,但我怎样才能将其转换为 swift?
我有一个带有自定义 TableViewCells 的 UITableView,它有一个名为“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
}
}
现在,按钮操作方法:
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!
我在这里做错了什么?
最佳答案
尽量不要将所选标记用作此类单元格状态的切换。选择一个单元格后,再次点击它不会取消选择。相反,您可以只使用 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 方法是不必要的。除非您需要自定义动画,否则单独使用 beginUpdates() 和 endUpdates() 应该可以解决问题。
关于ios - UITableView:单击按钮时如何动态更改单元格高度? swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35515597/