Vis*_*tel 6 uitableview ios swift
我可以从这里告诉如何在objective-c中执行此操作,但是如何将其转换为swift?
我有一个带有自定义TableViewCells的UITableView,它有一个名为"expandButton"的UIButton.我试图找出如何在单击该单元格的expandButton时更改该特定单元格的高度.
此外,再次单击时,它应更改回原始大小.我不熟悉ObjectiveC所以请在Swift中帮助我.提前谢谢!
这是我到目前为止:
//Declaration of variables as suggested
var shouldCellBeExpanded:Bool = false
var indexOfExpendedCell:NSInteger = -1
Run Code Online (Sandbox Code Playgroud)
现在在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
}
}
Run Code Online (Sandbox Code Playgroud)
现在,按钮动作方法:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
最后是HeightForRowAtIndexPath
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if shouldCellBeExpanded && indexPath.row == indexOfExpendedCell {
return 166.0
}
else { return 91.0 }
}
Run Code Online (Sandbox Code Playgroud)
我想我错过了一些东西,因为当单击一次时单元格确实会膨胀,但它不会"收缩"回到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)
}
}
Run Code Online (Sandbox Code Playgroud)
另外,根据我的经验,reloadRowsAtIndexPath方法是不必要的.除非您需要自定义动画,否则单独使用beginUpdates()和endUpdates()应该可以解决问题.
| 归档时间: |
|
| 查看次数: |
3419 次 |
| 最近记录: |