Search code examples
iphoneswiftxcodetableviewxib

go to VC from button inside xib file that is used as a tableHeaderView


I have a TableSectionHeader xib file with a button in it (and some other stuff). This xib file is used as the custom header of a UItableview inside my PostViewController.

I want to be able to click on that button to show the detail about the cell. However, as the button is INSIDE the xib file, the IBAction is inside the TableSectionHeader.Swift (which inherits from UITableViewHeaderFooterView). This means that I can not segue or instantiate a VC.

How could I go from this button that is inside the xib file to another VC?


Solution

  • You need to get an outlet of your button into your xib class not an action , and when you create and return the header in your view controller , you will have a reference of your button before you return the header, then addTarget to your button and tag with selector to the method that is going to handle going to your next view controller .

    In your xib class drag and connect the button :

    class YearSectionHeader : UITableViewHeaderFooterView {
    
    @IBOutlet car button :UIButton!
    
    }
    

    In your view controller table view header method (example) don't forget to change the class to and identifier to the correct one your using:

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
            let header : YearSectionHeader = tableView.dequeueReusableHeaderFooterViewWithIdentifier("TableHeader") as! YearSectionHeader
            header.button.addTarget(self, action: #selector(self.handlingMethodName(_:)), forControlEvents: UIControlEvents.TouchUpInside)
            header.button.tag = section
            return header
    
        }
    

    sender.tag is your section number, you can perform the segue here :

    func handlingMethodName(sender:UIButton){
    
            print(sender.tag)
    
        }