简体   繁体   中英

How to get the header section title from selected tableview cell?

I am having a tableview which has several section. What I want is when I select a particular tableview cell from section I want title header of that section. I looked several SO question but didn't find out anything useful. Thanks in advance.

You can get title with following code on tableviewcell click method

UITableViewHeaderFooterView* header =[self.tableView headerViewForSection:indexPath.section];
NSLog(@"Header text = %@", header.textLabel.text);

In Swift

let sectionHeaderView = table.headerViewForSection(indexPath.section)
let sectionTitle = sectionHeaderView?.textLabel?.text

Try following to get title if you are using "titleForHeaderInSection" table delegate :

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let title = self.tableView(tableView, titleForHeaderInSection: indexPath.row)

    }

Swift 4 : using cell button click

    let buttonPosition:CGPoint = sender.convert(.zero, to:self.mytable)
    let indexPath12 = self.mytable.indexPathForRow(at: buttonPosition)

    let intSection : Int = (indexPath12?.section)!
    let intRow : Int = (indexPath12?.row)!

    let myHeaderView = tableView(self.mytable, viewForHeaderInSection: indexPath?.section)
    let labels = myHeaderView?.subviews.compactMap { $0 as? UILabel }

    var sectioTitle = ""
    for label in labels! {
        // you will get your title
        sectioTitle = label.text!
    }

Swift 4 : using uitablview didselect method

    let myHeaderView = tableView(self.mytable, viewForHeaderInSection: indexPath?.section)
    let labels = myHeaderView?.subviews.compactMap { $0 as? UILabel }

    var sectioTitle = ""
    for label in labels! {
        // you will get your title
        sectioTitle = label.text!
    }

I was experiencing this issue in a unit case. My use case: no custom header and using the UITableViewDataSource method tableView(_:titleForHeaderInSection:) to return a string for each section. headerView(forSection:) returns nil but numberOfSections returns the correct number of sections, rect(forSection:) returns the correct frame, and, most puzzling, the visual debugger shows the sections as type UITableViewHeaderFooterView .

I was finally able to retrieve the titles for my sections by calling the dataSource method tableView(_:titleForHeaderInSection:) :

tableView.dataSource?(tableView, titleForHeaderInSection: 0)

Seemingly odd behavior, as it seems like UIKit is using UITableViewHeaderFooterView to create headers when just a string is passed to the tableView(_:titleForHeaderInSection:) method. One would think you'd be able to retrieve them using headerView(forSection:) .

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