简体   繁体   中英

How to find TableView section header Index Path?

I want to do some kind of action according to the TableView Section Header Index Path. Is there any method to trace the section header Index Path?

Short Answer

There is no existing method for that.

Solution

Declare a section number variable in your custom header class.

class CustomHeader: UITableViewHeaderFooterView
{

//
// MARK :- PROPERTIES
//

var sectionNumber: Int!

//
// MARK :- METHODS
//

override func awakeFromNib()
{
    super.awakeFromNib()
    
    // Initialization code ...
}

func configureWith(_ section: Int)
{
    self.sectionNumber = section
}

} // end of class

Then in your view controller inside viewForHeaderInSection , assign section value while instantiating your custom header.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "selectHeaderIdentifier") as! CustomHeader
    header.configureWith(section)
    return header
}

Now, you have in your custom header a section number property, use it as you want :]

header.sectionNumber

how about func headerViewForSection ?

override func tableView(tableView: UITableView, headerViewForSection section: Int) -> UITableViewHeaderFooterView {

    let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell")        

    // do some stuf, e.g.
    switch (section) {
    case 0:
        headerCell.backgroundColor = UIColor.cyanColor()
    default:
        headerCell.backgroundColor = UIColor.redColor()
    }

    return headerCell
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM