Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding UITapGestureRecognizer to XIB

I've created a custom XIB extending from UITableViewHeaderFooterView and attempting to add a gesture recognizer. Only problem is attempting to add the recognizer via interface builder results in the object being added to the top level hierarchy and the following error causing my app to crash:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'invalid nib registered for identifier (AccordionHeader) - nib must contain exactly one top level object which must be a UITableViewHeaderFooterView instance'

To the best of my knowledge there's no "viewDidLoad" equivalent available or I would just be adding the recognizer programmatically. Is there another way to do this?

like image 813
AnthonyOSX Avatar asked May 04 '26 15:05

AnthonyOSX


1 Answers

Try This

Step 1:- Register XIB file

func regXib(){
 self.tblList.register(UINib(nibName: "YourCellName", bundle: nil), forHeaderFooterViewReuseIdentifier: "YourCellNameIdentifierName")
}

Step:- 2 viewForHeaderInSection Method

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "YourCellNameIdentifierName") as! YourCellName
        let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.expand))
        cell.layer.backgroundColor = UIColor.white.cgColor
        cell.addGestureRecognizer(recognizer)
        cell.tag = section
        return cell
    }

Step 3:- Tap Gesture Action

@objc func expand(sender:UITapGestureRecognizer){
   let tag = (sender.view?.tag)!
   // Tap Action Code Here 
}
like image 191
Amul4608 Avatar answered May 06 '26 10:05

Amul4608



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!