展开当前单元格时折叠其他 UITableViewCell [英] Collapse other UITableViewCell when current cell is expanded
本文介绍了展开当前单元格时折叠其他 UITableViewCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试扩展我的 UITableViewCell
并且我可以扩展单元格.但我想折叠未选中的 UITableViewCell
.
I am trying to expand my UITableViewCell
and I can expand cells. But I want to collapse the UITableViewCell
which are not selected.
我在代码中尝试的内容:
What I am trying in code:
var expandedCells = [Int]()
@IBOutlet weak var tableVieww:UITableView!
@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
tableVieww.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! exampleCell
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 212
} else {
return 57
}
}
推荐答案
您可以维护一个变量来维护选定的索引,如下所示,
You can maintain a variable for maintaining the selected index as below,
var expandedIndexPath: IndexPath?
然后按如下方式更新您的 tableView 委托,
Then update your tableView delegate as follows,
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
expandedIndexPath = indexPath // Update the expandedIndexPath with the selected index
tableView.reloadData() // Reload tableview to reflect the change
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Check wether expanded indexpath is the current index path and updated return the respective height
if expandedIndexPath == indexPath {
return 212
} else {
return 57
}
}
这应该可以正常工作.
这篇关于展开当前单元格时折叠其他 UITableViewCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文