Swift - how to make custom header for UITableView?

后端 未结 7 801
说谎
说谎 2020-12-23 13:57

I need to add custom header to my table

I try this

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    l         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 14:18

    If you are willing to use custom table header as table header, try the followings....

    Updated for swift 3.0

    Step 1

    Create UITableViewHeaderFooterView for custom header..

    import UIKit
    
    class MapTableHeaderView: UITableViewHeaderFooterView {
    
        @IBOutlet weak var testView: UIView!
    
    }
    

    Step 2

    Add custom header to UITableView

        override func viewDidLoad() {
                super.viewDidLoad()
    
                tableView.delegate = self
                tableView.dataSource = self
    
                //register the header view
    
                let nibName = UINib(nibName: "CustomHeaderView", bundle: nil)
                self.tableView.register(nibName, forHeaderFooterViewReuseIdentifier: "CustomHeaderView")
    
    
        }
    
        extension BranchViewController : UITableViewDelegate{
    
        }
    
        extension BranchViewController : UITableViewDataSource{
    
            func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
                return 200
            }
    
            func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                let headerView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView" ) as! MapTableHeaderView
    
                return headerView
            }
    
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: 
    
        Int) -> Int {
                // retuen no of rows in sections
            }
    
            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
                // retuen your custom cells    
            }
    
            func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
            }
    
            func numberOfSections(in tableView: UITableView) -> Int {
                // retuen no of sections
            }
    
            func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
                // retuen height of row
            }
    
    
        }
    

提交回复
热议问题