【问题标题】:Swift 3 - button in .xib custom tableviewcell is not performing action.xib 自定义 tableviewcell 中的 Swift 3 - 按钮未执行操作
【发布时间】:2017-02-06 15:31:32
【问题描述】:

我有一个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”从未被打印。我错过了什么?

【问题讨论】:

    标签: ios uitableview swift3 addtarget


    【解决方案1】:

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

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

    cell.myButton.addTarget(self,action: #selector(myAction(sender:)), for: .touchUpInside)
    

    【讨论】:

    • 谢谢。实际上,我之前将它作为 addTarget 使用,但语法不正确,在寻找修复程序时发现了操作......非常感谢您的帮助。
    • @Dave 欢迎朋友 :)
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2019-12-13
    相关资源
    最近更新 更多