UITableView grouped之调整任意header、footer首尾高度

本文介绍如何使用Swift通过自定义UITableView的样式来实现特定的UI效果,包括如何设置tableView的背景颜色、高度以及如何使用不同的表格格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现思路:
用.plain格式的tableView,tableView 的背景色设置为 UIColor.groupTableViewBackground;
然后在代理中任由你自定义各种高度,避免使用 .grouped 格式的表格。

class ELTableControllerGrouped: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var table: UITableView!
     
    var sectionCount = 5
    var heightForFooter: CGFloat = 18
    var heightForHeader: CGFloat = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        table = UITableView(frame: view.bounds, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(UITableViewCell.self, forCellReuseIdentifier: "c")
        table.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "v")
        view.addSubview(table)
        table.backgroundColor = UIColor.groupTableViewBackground 
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "c") 
        cell?.textLabel?.text = "dd d"
        return cell! 
    }
     
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return section == sectionCount-1 ? 0 : heightForFooter
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let v1 = tableView.dequeueReusableHeaderFooterView(withIdentifier: "v")!
        v1.contentView.backgroundColor = UIColor.groupTableViewBackground
        return section == sectionCount-1 ? nil : v1
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionCount
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4 
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值