单击每个部分时展开表视图部分



我有一个表格视图,其中有 2 个部分,每个部分下方有一些单元格(可以是动态的(,显示相关数据。

这是我为显示数据而编写的代码...

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return recentUsers?.count
} else {
return groupNameArray?.count
}
}

func numberOfSections(in tableView: UITableView) -> Int {
return 2
}


func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "  CHAT LIST"
} else {
return "  GROUPS"
}
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RecentMessageCell
cell.tag = indexPath.row
if indexPath.section == 0 {
if let user = recentChatUsers?[indexPath.row] {
cell.idLabel?.text = user.id
}
} else {

if groupNameArray.isEmpty == false {
let grpArr = groupNameArray[indexPath.row]
cell.userNameLabel?.text = grpArr.grpname
}
}
return cell
}

现在我想要实现的是,如果我单击第一部分,它应该展开并显示它包含的单元格,第二个单元格也应该发生同样的情况。再次单击每个部分应该隐藏已展开的单元格。

我确实在互联网上搜索了解决方案。但是,尽管有可用的资源,但我找不到太多帮助来解决我的问题......

添加一个数组来跟踪部分扩展/折叠

let sectionStats = [Bool](repeating: true, count: 2)

添加 a、IBAction 以跟踪部分抽头、更新相应部分的sectionStats值并重新加载部分

并更新您的numberOfRowsInSection,如下所示

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard sectionStats[section] else {
return 0
}
if section == 0 {
return 1
} else {
return list.count
}
}

可点击标头:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return headerView(section: section, title: section == 0  ? "CHAT LIST" : "GROUPS")
}
private func headerView(section: Int, title: String) -> UIView {
let button = UIButton(frame: CGRect.zero)
button.tag = section
button.setTitle(title, for: .normal)
button.setTitleColor(UIColor.red, for: .normal)
button.addTarget(self, action: #selector(sectionHeaderTapped), for: .touchUpInside)
return button
}
@objc private func sectionHeaderTapped(sender: UIButton) {
let section = sender.tag
sectionStats[section] = !sectionStats[section]
tableView.beginUpdates()
tableView.reloadSections([section], with: .automatic)
tableView.endUpdates()
}

关于如何构建具有可折叠部分的表视图的好教程: https://medium.com/ios-os-x-development/ios-how-to-build-a-table-view-with-collapsible-sections-96badf3387d0

这种功能需要更多的代码,我不能在这里编写整个代码,但我可以向您解释将用于实现此目的的概念,并将附上一些很好的教程,我用来最终创建这样的功能


  1. 首先,您需要为分区创建自定义HeaderView
  2. 接下来,您需要在部分上UITapGestureRecognizer,并且需要在UITapGestureRecognizer构造函数action部分中提供的函数中写入登录名
  1. 您需要在HeaderView文件中创建一个单独的Protocol,包含您的TableViewViewController将采用该协议,并将处理是扩展行还是折叠行
  1. 此外,您需要为每个部分创建一个单独的Struct实例,该实例将包含一个boolean variable,该将指示该部分是展开还是折叠

这是在iOS中创建Expandable List时需要的基本概念。

下面我附上了一些教程的链接:

教程 1

教程 2

教程 3

教程4