![](https://img.haomeiwen.com/i1402122/4feea8bbcd6f5f5c.jpg)
实现这个功能的思路是创建一个tableView的sectionHeaderView,添加点击事件,从而控制cell在每一个section的数量。
首先我们需要创建一个数组来装section的headerView的数据,我们设为dataArray
//注意model为网络请求对应的model
var dataArray:[model] = []
var isSelcect = false
var flagArray: [Bool] = []//这个数组是用来装每一个section对应的布尔值的
//这个函数是根据dataArray的内容来创建一个每一个section对应的布尔值的数组
func makeData(){
if dataArray.count < 1 {
return
}else{
for _ : NSInteger in 0...dataArray.count - 1 {
flagArray.append(false)
}
}
}
//创建sectionHeaderView
fun setSectionHeaderView(section:Int)->UIView{
//这里面就是创建sectionHeaderView的代码我这里只创建一个按钮
let sectionView = UIButton.init(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 64))
sectionView.tag = section + 100
isSelcect = flagArray[section]
sectionView.addTarget(self, action: #selector(buttonClinck(sender:)), for: .touchUpInside)
sectionView.backgroundColor = UIColor.white
return sectionView
}
//点击事件的实现
func buttonClinck(sender:UIButton) {
isSelcect = !isSelcect
let ratio : NSInteger = sender.tag - 100
if self.flagArray[ratio] {
self.flagArray[ratio] = false
}else{
self.flagArray[ratio] = true
}
tableView?.reloadSections(IndexSet.init(integer: sender.tag - 100), with: .fade)
}
//UITableViewDelegate
extension AZProductViewController:UITableViewDelegate{
//实现sectionView的代理
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if self.dataArray.count < 1 {
return nil
}
let model = self.dataArray[section]
return self.setSectionHeaderView(section: section)
}
//返回HeaderInSection高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 64
}
}
//UITableViewDataSource
//数据源
extension AZProductViewController:UITableViewDataSource{
//section的个数
func numberOfSections(in tableView: UITableView) -> Int{
return self.dataArray.count
}
//每一个section的cell个数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if flagArray.count < 1 {
return 0
}else{
if flagArray[section] {
return 1
}else{
return 0
}
}
}
}
其他数据源,代理方法,tableview的创建都是正常处理。
如果需要更多层的tableview实现建议参考这篇文章http://www.jianshu.com/p/4abf7ebf7017
https://github.com/Augustyniak/RATreeView
网友评论