首页 文章

无法单击UITableViewCell内的按钮?

提问于
浏览
1

我正在使用storyboard创建一个UITableView,加载一些数据以推荐用户关注,并在单元格中包含一个跟随按钮 .

唯一的问题是,我无法点击单元格内的关注按钮 .

这是我的ViewController类中TableView的代码(它不是TableViewController,它是一个包含UITableViewDelegate和UITableViewDataSource的UIViewController):

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")
}

这是TableViewCell类的代码 .

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)
}
}

我以前在StackOverflow上看过这个问题,但我无法解决问题 . 以下是我尝试过的一些事情:

  • 为tableView,单元格,内容视图和按钮启用/禁用用户交互的众多变体 .

  • 使用以下代码将按钮移动到内容视图的前面: followCell.bringSubview(toFront: followCell.followButton)

  • 我已经尝试过本教程中显示的委托/协议方法:http://candycode.io/how-to-properly-do-buttons-in-table-view-cells/

我似乎无法让它工作 .

有没有其他人有这个问题,并找到了解决方案?

提前致谢!

1 回答

  • 1

    我查了一下 - 你的代码运行正常 . 您可能没有为单元格上的按钮设置IBOutlet,无论是在Storyboard中,还是在单独的.xib文件中(如果使用它) . 打开故事板并将单元格中的插座与按钮匹配,如下所示:

    Set the outlet from your cell to the UIButton in Interface Builder

相关问题