I trying to use expandable tableview in swift. So I added Gesture to header in tableview, but it does not recognising. Kindly guide me. Just cross check my coding.
MY CODING IS BELOW:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let vvv = tableView.headerViewForSection(section)
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
tap.delegate = self
vvv?.addGestureRecognizer(tap)
return vvv
}
func handleTap(gestureRecognizer: UITapGestureRecognizer)
{
if(gestureRecognizer.state == .Ended)
{
println("SECTION PRESSED") //NOT ENTERING TO THIS BLOCK
}
}
In Swift 4 you can add a UITapGestureRecognizer to the header view:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(headerTap))
headerView.addGestureRecognizer(tapRecognizer)
return headerView
}
@objc func headerTap() {
// Tap action
}
I did it this way.
First, make a UITableViewCell class with a "headerCellSection" variable (or whatever you want to call it for that matter).
import UIKit
class HeaderCellTableViewCell: UITableViewCell {
var headerCellSection:Int?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Add the cell to "viewForHeaderInSection":
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("headerCell") as! HeaderCellTableViewCell
return headerCell
}
Send the cell's section to the previously declared variable and add the tap gesture recogniser to the cell. The code should look something like this:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("headerCell") as! HeaderCellTableViewCell
// Send section
headerCell.headerCellSection = section
// Add gesture
let headerTapGesture = UITapGestureRecognizer()
headerTapGesture.addTarget(self, action: "myAction:")
headerCell.addGestureRecognizer(headerTapGesture)
return headerCell
}
Then add the action. In the action you can access the view that has the tap gesture target. There you can access tour "headerCellSection" value and voila!
func myAction (sender: UITapGestureRecognizer) {
// Get the view
let senderView = sender.view as! HeaderCellTableViewCell
// Get the section
let section = senderView.headerCellSection
print(section)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With