Swift 3 - .xib 自定义 tableviewcell 中的按钮未执行操作
Swift 3 - button in .xib custom tableviewcell is not performing action
我有一个 tableviewcontroller
,我在 .xib 文件中创建了自定义 tableviewcell。
按钮 (myButton) 用于 myCustomTableViewCell.xib 有一个出口到 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" 从未被打印。我错过了什么?
您需要使用 addTarget(_:action:for:)
method to add the action for your button not the actions(forTarget:forControlEvent:)
。
函数 actions(forTarget:forControlEvent:)
returns 已添加到控件的操作。它不添加 target/action
.
cell.myButton.addTarget(self,action: #selector(myAction(sender:)), for: .touchUpInside)
我有一个 tableviewcontroller
,我在 .xib 文件中创建了自定义 tableviewcell。
按钮 (myButton) 用于 myCustomTableViewCell.xib 有一个出口到 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" 从未被打印。我错过了什么?
您需要使用 addTarget(_:action:for:)
method to add the action for your button not the actions(forTarget:forControlEvent:)
。
函数 actions(forTarget:forControlEvent:)
returns 已添加到控件的操作。它不添加 target/action
.
cell.myButton.addTarget(self,action: #selector(myAction(sender:)), for: .touchUpInside)