0

我有一个tableviewcontroller,我在 .xib 文件中创建了自定义 tableviewcell。

myCustomTableViewCell.xib 上使用的按钮 (myButton) 有一个到 myCustomTableViewCell.swift 的出口

我在 TableViewController.swift 文件中为按钮设置了一个动作

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = Bundle.main.loadNibNamed("myCustomTableViewCell", owner: self, options: nil)?.first as! myCustomTableViewCell    

cell.myButton.setTitle(arrayOfMyData[indexPath.row].myText, for:.normal )

//other code to set some other cell.attribute values like above (all works)

cell.myButton.actions(forTarget: "myAction", forControlEvent: .touchUpInside)

}

在 TableViewController.swift 的其他地方我有这个动作:

func myAction(sender: UIButton){
    print("pressed myButton")
}

但 myAction 从未被调用/“pressed myButton”从未被打印。我错过了什么?

4

1 回答 1

4

您需要使用addTarget(_:action:for:)方法来为您的按钮添加操作,而不是actions(forTarget:forControlEvent:).

该函数actions(forTarget:forControlEvent:)返回已添加到控件的操作。它不添加target/action.

cell.myButton.addTarget(self,action: #selector(myAction(sender:)), for: .touchUpInside)
于 2017-02-06T15:44:06.843 回答