swift 分组表格 并含有有头部视图

首先应该在你想要添加表格的控制器上创建表格

 let tableV = UITableView.init(frame:  self.view.frame, style: UITableViewStyle.grouped)
        tableV.delegate = self
        tableV.dataSource = self
        
        self.view.addSubview(tableV)

别忘了遵守数据源协议
其次就是重点 分组了
举个例子
我们分三组,如果使用自定义表格的话 可以创建三继承于UItableviewcell的控制器,选择上xib这样会简单容易理解一些
下面就是代码了
在外面填写分组方法

func numberOfSections(in tableView: UITableView) -> Int {
        
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 || section == 2 {
            
            return 1
        }else{
            
            return 3
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
            
            return cell!
        }else if indexPath.section == 1{
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "two")
            
            return cell!
        }else {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "three")
            
            return cell!
        }
        
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }
    //返回分区头部视图
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.white
        let titleLabel = UILabel()
        titleLabel.text = "午安·北京"
        titleLabel.textColor = UIColor.black
        titleLabel.sizeToFit()
        
        headerView.addSubview(titleLabel)
        return headerView
    }
    
    //返回分区头部高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }

在didload里面注册cell

 //注册xib
        tableV.register(UINib.init(nibName: "OneTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        tableV.register(UINib.init(nibName: "TwoTableViewCell", bundle: nil), forCellReuseIdentifier: "two")
        tableV.register(UINib.init(nibName: "ThreeTableViewCell", bundle: nil), forCellReuseIdentifier: "three")
  

也是在里面我们填写表格头部视图的字体

      //设置分区头尾的文字颜色:黑色
        UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self])
            .textColor = UIColor.black
        //设置分区头尾的文字样式:20号斜体
        UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self])
            .font = UIFont.italicSystemFont(ofSize: 30)

然后在你的xib里面填写你想要用到的控件就完成啦!!

你可能感兴趣的:(swift 分组表格 并含有有头部视图)