1

I have this problem, hope you can help me out.

This is the code I have in viewForHeaderInSection :

let button = UIButton(frame: CGRect(x: view.frame.width - (cancel.frame.width + xImage.frame.width + 100), y: view.frame.origin.y, width: cancel.frame.width + xImage.frame.width + 120, height: view.frame.height))
button.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
button.addTarget(self, action: #selector(action), for: .touchUpInside)
view.addSubview(button)

and this is action func:

@objc func action(sender: UIButton) {
    let position: CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
    if let indexPath = self.tableView.indexPathForRow(at: position) {
        let section = indexPath.section
        print(section)
    }
}

Now if I tap on every header except the first one (header 0) it prints the correct section. How to make it to detect the header 0 too?

Nishant Bhindi
  • 2,242
  • 8
  • 21
Elia Crocetta
  • 318
  • 1
  • 6
  • 20

1 Answers1

2

If you want to know which is the button's section, you might assign the section to the button's tag, eg:

in your viewForHeaderInSection

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
   let button = UIButton(frame: CGRect(x: view.frame.width - (cancel.frame.width + xImage.frame.width + 100), y: view.frame.origin.y, width: cancel.frame.width + xImage.frame.width + 120, height: view.frame.height))
   button.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
   button.addTarget(self, action: #selector(action), for: .touchUpInside)
   view.addSubview(button)
   button.tag = section // this is the trick
}

and then inside the action:

@objc func action(sender: UIButton) {
    let section = sender.tag
    print(section)
}
mugx
  • 9,869
  • 3
  • 43
  • 55