UITableView自定义TableHeader和TableFooter

本文详细介绍了如何在iOS应用中使用UITableView自定义头部和尾部视图,包括创建CustomHeaderView和CustomFooterView的步骤,以及在UIViewController中注册和显示它们的方法。

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

UITableView自定义TableHeader和TableFooter

我猜你希望的效果是这样的

在这里插入图片描述

自定义页眉视图
让我们创建一个文件名 UITableViewHeaderFooterView 的 CustomerHeaderView 子类。
在这里插入图片描述
现在让我们创建视图的 Xib 文件并将其命名为 CustomHeaderView。

在这里插入图片描述

更改高度标题视图在创建的 XIB 文件中选择视图。在属性检查器中选择大小并将其大小设置为自由度

在这里插入图片描述

自定义页脚视图 让我们创建一个文件名 UITableViewHeaderFooterView 的客户页脚视图
子类并重复上述步骤。

在主类文件中,寄存器头视图和页脚视图在视图中的表视图DidLoad

class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "CustomHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "CustomHeaderView")
tableView.register(UINib(nibName: "CustomFooterView", bundle: nil), forHeaderFooterViewReuseIdentifier: "CustomFooterView")
  }
}
 
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let indentifier = "CustomHeaderView"
        let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: indentifier)
        if section == 0 {
            cell?.contentView.backgroundColor = .cyan
        }
        if section == 1 {
            cell?.contentView.backgroundColor = .red
        }
       
   
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let indentifier = "CustomHeaderView"
        let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: indentifier)
        cell?.contentView.backgroundColor = UIColor.tableSectionColor()
        
        return cell
    }
   
 
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
       
        
        
        return 100
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
      
        
        return 50 
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值