我有一个 UITableview,其中每个单元格都有一个按钮。
我的问题是,如果我单击第一行中的按钮,单元格的高度会增加,然后我单击 tableviewcell 中的另一个按钮,已展开的单元格高度将减小,选定的单元格高度将增加
尝试此链接后UITableView:单击其中的按钮时如何动态更改单元格高度?迅速 https://stackoverflow.com/questions/35515597/uitableview-how-to-change-cell-height-dynamically-when-a-button-is-clicked-in-i
这是我的代码:
var indexOfExpendedCell:NSInteger = -1
var shouldCellBeExpanded:Bool = false
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
cell.optionButton?.addTarget(self, action: #selector(ViewController.optionAction), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if shouldCellBeExpanded && indexPath.row == indexOfExpendedCell {
return 102
}
else { return 57 }
}
}
func optionAction(sender: UIButton){
if let button = sender as? UIButton {
shouldCellBeExpanded = !shouldCellBeExpanded
indexOfExpendedCell = sender.tag
if shouldCellBeExpanded {
self.tableView.beginUpdates()
self.tableView.endUpdates()
button.setImage(UIImage(named: "Reject Icon filled"), forState: .Normal)
}
else {
self.tableView.beginUpdates()
self.tableView.endUpdates()
button.setImage(UIImage(named: "Reject Icon"), forState: .Normal)
}
}
}
尝试此代码后,当我单击同一行中的按钮时,单元格高度会扩展和减小。我未能执行以下步骤
脚步 :
1.点击第二行单元格高度扩大
2.现在单击第一行,我需要减少第二行的高度并扩大第一行的高度
谁能帮我?
创建一个数组来保存应扩展的单元格。当按下按钮时,相应地向数组添加或删除元素。这是代码:
// Initialize an empty array of integers
var expandedCells = [Int]()
@IBAction func buttonPressed(_ sender: AnyObject) {
// If the array contains the button that was pressed, then remove that button from the array
if expandedCells.contains(sender.tag) {
expandedCells = expandedCells.filter({ $0 != sender.tag})
}
// Otherwise, add the button to the array
else {
expandedCells.append(sender.tag)
}
// Reload the tableView data anytime a button is pressed
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
// Set the tag on your button to be equal to indexPath.row
// This allows @IBAction func buttonPressed(_ sender: AnyObject) above to discern which row was tapped
cell.myButton.tag = indexPath.row
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Set the row height based on whether or not the Int associated with that row is contained in the expandedCells array
if expandedCells.contains(indexPath.row) {
return 102
} else {
return 57
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)