Can't click button inside UITableViewCell?

谁说我不能喝 提交于 2019-12-11 08:45:09

问题


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

Only problem is, I'm not able to click the follow button inside the cell.

Here's the code for the TableView in my ViewController class (It isn't a TableViewController, it's 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's 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've seen this question on StackOverflow before, but I wasn't able to fix the problem. Here are some things I've tried:

  • Numerous variations of enabling/disabling user interaction for the tableView, cell, content view, and button.
  • Moving the button to the front of the content view using this code: followCell.bringSubview(toFront: followCell.followButton)
  • I've 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 seem to get it to work.

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

Thanks in advance!


回答1:


I checked - your code works fine. You probably don't have IBOutlet set for your button on the cell, either in Storyboard, (or in separate .xib file if you use it). Open your storyboard and match the outlet from the cell to button, like this:



来源:https://stackoverflow.com/questions/43224392/cant-click-button-inside-uitableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!