首页 > 解决方案 > Swift 当我使用 didSelectRowAt 时,Custom Cell 应该如何加载 tableview 数据并使其扩展?

问题描述

我创建了一个包含 tableview 的自定义单元格

这是 MainTableView 和数据

var data = [People(name:"Kevin",age:"18",tall:"180")]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath) as! MainTableViewCell

cell.title = data[indexPath.row].name
cell.detail = ["age \(data[indexPath.row].age)","tall \(data[indexPath.row].tall)"]
cell.isExtend = false

return cell

}

我尝试点击单元格以扩展 tableView 高度并加载数据

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath) as! MainTableViewCell

cell.isExpand = !cell.isExpand

}

这是 MainTableViewCell

class MainTableViewCell: UITableViewCell {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var detailTableView: UITableView!
@IBOutlet weak var detailTableViewHeight: NSLayoutConstraint!

var detail:[String] = []{
didSet{
detailTableView.reloadData()
}
}

var isExpand: Bool = false{
didSet{
detailTableView.isHidden = !isExpand
detailTableView.reloadData()
detailTableViewHeight.constant = isExpand ? detailTableView.contentSize.height:0
}
}

override func awakeFromNib() {
        super.awakeFromNib()
        detailTableView.delegate = self
        detailTableView.dataSource = self
        detailTableView.isScrollEnabled = false
        detailTableViewHeight.constant = 0
    }
}

我使用 tableView 加载数据并首先隐藏一些主题,然后点击显示和隐藏主题

但什么也没发生

我忘了什么吗?

标签: swiftuitableview

解决方案


在 cellforRowAt 中:

let cell: MoreUserDetails = tableView.dequeueReusableCell(withIdentifier: "MoreUserDetails") as! MoreUserDetails
cell.backgroundColor = .clear
cell.selectionStyle = .none
if isExpand {
// your func when its expanded
}
else {
// your func when its hidden
}
return cell

在没有选择

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
if isSelected[indexPath.row] {
                    isExpand[indexPath.row] = false
                }
                else {
                    isExpand[indexPath.row] = true
                }
                self.tableVIew.reloadData()
}

推荐阅读