2

I have a UITableViewCell with a button inside of it. (made through IB).

Now what I'd like to do is the following:

  1. When pressing the UITableViewCell, I'd like to trigger a segue.
  2. When pressing the UIButton, I'd like to trigger an action.

However, what actually happens is that the UITableViewCell gets selected when the button is pressed, instead of the desired result.

Is there a way around it that enables both actions at the same time?

Thanks.

-- Edit

I'd like to be able to select the table cell still, AND be able to press the button. So disabling selection wouldn't work.

-- As requested, the code for the cellForRowAt: method

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: PersonTableViewCell.identifier, for: indexPath) as! PersonTableViewCell

    if ( indexPath.row < (self.searchResult.count)) {
        cell.configure(searchResult[indexPath.row])
    }

    return cell
}

Then, inside of the configure function of the cell, a UITapGestureRecognizer is created on the button that triggers the following function:

func follow(profile: User) {
    self.followButton.isSelected = !self.followButton.isSelected
    profile.toggleFollow(callback: { _ in })
}
ilikecode
  • 391
  • 3
  • 14

1 Answers1

3

Ensure following points for your button inside cell.

  1. User interaction for is enabled for your button
  2. Button has proper frame size (tappable area)
  3. A valid button action is assigned/connected to button
  4. Button is top most view (there is no other view covering button)

Show your code for cellForRow(atIndex... and your table view cell class to get exact solution.

Here is sample code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
    cell.yourbutton.isUserInteractionEnabled = true
    cell.yourbutton.addTarget(self, action: #selector(self.buttonTapped(sender:)), for: UIControlEvents.touchUpInside)

    //cell.bringSubview(toFront: cell.yourbutton)
    //cell.contentView.bringSubview(toFront: cell.yourbutton)

    return cell
}


@objc func buttonTapped(sender: UIButton) {
    print("button tapped")
}

Edit: Button has its own control actions/events handler. You may not need to add UITapGestureRecognizer.

Krunal
  • 77,632
  • 48
  • 245
  • 261