Can't click a button inside a UITableViewCell?

I use the storyboard to create a UITableView, loading some data to recommend users to follow, and including the follow button inside the cell.

The only problem is that I cannot click the follow button inside the cell.

Here is the code for the TableView in my ViewController class (this is not a TableViewController, it is a UIViewController that includes UITableViewDelegate and UITableViewDataSource):

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return followRecommendations.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let followCell = tableView.dequeueReusableCell(withIdentifier: "followCell", for: indexPath) as! FollowRecommendationTableViewCell followCell.followButton.tag = indexPath.row followCell.followButton.addTarget(self, action: #selector(self.buttonTapped), for: UIControlEvents.touchUpInside) followCell.followRecommendationName.text = followRecommendations[indexPath.row].suggestedUserName followCell.followRecommendationInterests.text = followRecommendations[indexPath.row].suggestedUserTasteString let imageUrl = followRecommendations[indexPath.row].suggestedUserImage followCell.followRecomendationImage.downloadedFrom(link: imageUrl) return followCell } func buttonTapped() { print("Tapped") } 

and here is the code for the TableViewCell class.

 class FollowRecommendationTableViewCell: UITableViewCell { @IBOutlet weak var followRecomendationImage: UIImageView! @IBOutlet weak var followRecommendationName: UILabel! @IBOutlet weak var followRecommendationInterests: UILabel! @IBOutlet weak var followButton: UIButton! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } 

I already saw this question in StackOverflow, but I could not solve the problem. Here are a few things I've tried:

  • Numerous options for enabling / disabling user interaction for presenting a tableView, cell, content, and button.
  • Move the button to the beginning of the content view with this code: followCell.bringSubview(toFront: followCell.followButton)
  • I tried the delegate / protocol method shown in this tutorial: http://candycode.io/how-to-properly-do-buttons-in-table-view-cells/

I just can't get it to work.

Has anyone else had this problem and figured out a solution?

Thanks in advance!

+1
uitableview swift3 uibutton tableview
source share
1 answer

I checked - your code is working fine. You probably don't have an IBOutlet for your button on a cell, either in the Storyboard or in a separate .xib file if you use it. Open the storyboard and map the output from the cell to the button, for example:

Set output from your cell to UIButton in Interface Builder

+1
source share

All Articles