others-how to catch tap event for a button inside tableviewcell of an iOS app

1. Purpose

In this post, I would demo how to catch the tap event for buttons inside a table view cell when developing an iOS app.

2. Environment

  • Mac OS 10.15
  • Swift 5
  • Xcode 12

3. The solution

3.1 The UI layout

Suppose we have a table view controller , which shows a button inside its static cells, just as follows:

When we clicked the button, we found that the button did not catch the tap event, the table cell was selected instead. That was not what we want. How to pass through the tap event to the button?

3.2 Solve the problem

We should change the table view cell to be unselectable, just select the cell in the story board, then change its selection mode to none, just as follows:

image-20210428081217183

According to apple’s developer document about UITableViewCell.SelectionStyle:

case none

The cell has no distinct style for when it is selected.

case blue

The cell has a default background color when selected.

case gray

Then cell when selected has a gray background.

case default``

The cell selection style to use for tables. This is the default value.

After change, we can set up an IBAction for the button inside the cell by control-dragging the button to our viewcontroller.swift, then we get this:

    @IBAction func onClickButton1(_ sender: UIButton) {
        print("button inside cell clicked")
    }

Run the app again, when we click the button inside the cell, we get this message in the debug console:

button inside cell clicked

Now it works!

4. Summary

In this post, I demonstrated how to make the button inside a tablecell clickable, make sure you have disabled the selection of the cell by choosing the ‘none’ selection type.