Swift - 自定义 TableView 未执行单击 UIButton

Swift - Custom TableView Not Executing Click on UIButton

我正在尝试使用 Swift 完成我认为是一项简单的任务。我创建了一个 Custom TableView Cell 并向其添加了一个按钮。我希望能够在您单击按钮时看到一些动作发生。不幸的是,当我点击按钮时没有任何反应。有人可以阐明这一点吗?我把代码放在下面:

自定义 TableView 单元格:

import UIKit

class TestTableViewCell: UITableViewCell {

@IBOutlet weak var testBtn: UIButton!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
func buttonTappedOnCell()
{
    println("buttonTapped!")
}

}

下面是正在调用的视图控制器中的代码:

  func tableView(tableView: UITableView,
    cellForRowAtIndexPath
    indexPath: NSIndexPath) -> UITableViewCell {
        tableView.registerNib(UINib(nibName:"TestTableViewCell", bundle:nil), forCellReuseIdentifier:"TestButtonCell")
 let cell =
        tableView.dequeueReusableCellWithIdentifier("TestButtonCell", forIndexPath: indexPath) as TestTableViewCell

           cell.testBtn.addTarget(cell, action: "buttonTappedOnCell", forControlEvents: UIControlEvents.TouchDown)
        return cell
}

我还尝试更改调用以包含“:”-> cell.testBtn.addTarget(cell, action: "buttonTappedOnCell:", forControlEvents: UIControlEvents.TouchDown) 但这没有用。我尝试的另一件事是将调用函数移动到视图控制器中,并将目标操作指向自身。不幸的是,这也不起作用。这种工作的一个简单例子会很棒。在一天结束时,希望能够有一个自定义 table 视图单元格,其中包含 6 个单选按钮,允许用户 select 只有一个。但此时宝宝先一步。感谢您的帮助。

我认为问题是由您在代码中指定的事件引起的。

 cell.testBtn.addTarget(cell, action: "buttonTappedOnCell", forControlEvents: UIControlEvents.TouchDown)

ToouchDown 更改为 TouchUpInside

cell.testBtn.addTarget(cell, action: "buttonTappedOnCell", forControlEvents: UIControlEvents.TouchUpInside)

另外,为什么要以编程方式设置它?根据您的代码,我认为您的故事板上有按钮。那么为什么要以编程方式添加 IBAction 呢? (因为该操作也在同一 class 上调用)。

将您的 buttonTappedOnCell 声明为 IBAction 并将其直接连接到 storyboard/xib 上的按钮。