Reputation: 2890
I have a button inside a tableview cell (as shown in the below image), when I click the button,
didSelectRowAt indexpath
is not being triggered, could some one please suggest how I could do this ?
Please note: I am performing a set of actions on click of the button, in addition I would also like
didselectRowAt indexPath
to be triggered.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Table view cell has been clicked")
}
Upvotes: 5
Views: 4133
Reputation: 385
When you have multiple views in the cell they may receive the touch event and not the "cell" so didSelectRowAt will not be triggered. In that case add view.isUserInteractionEnabled = false
to each view, label or button.
Upvotes: 3
Reputation: 3385
If you are adding button or gesture on UITableViewCell
, didselectRowAt indexPath
not invoked . You can add button on remaining UI UITableViewCell
than clear color apply on button . User didn't show button and you can perform didselectRowAt indexPath
method task . If you wanna indexpath
in button method code give below.
func btnChildDropDown(sender:UIButton)
{
let cell = sender.superview?.superview as! ChildAgeTableViewCell
let indexPath = self.tblViewAddRooms.indexPath(for: cell)
}
Upvotes: 1
Reputation: 291
Put the outlet to the button inside a custom cell class. Then set tag and add selector for button in cellForItemAt. This example is for colletionView just change to suit tableView.
If you want the button in each cell this is how you have to do it. Adding a static button to a single cell won't call didSelectItemAt because your tapping a button that doesn't have reference to a reusable cells indexPath.
This way we send the button.tag tot he function so we know which cell the button is related to.
class MyClassViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
.... // Stuff
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
....// Create Cell
cell.deleteCellButton.tag = indexPath.item
cell.deleteCellButton.addTarget(self, action: #selector(MyClassViewController.deleteCellButtonTapped(_:)), for: .touchUpInside)
return cell
}
func deleteCellButtonTapped(_ sender: Any) {
... // Stuff
print("Selector called")
}
}
Upvotes: 0