【发布时间】:2016-12-27 17:51:37
【问题描述】:
我有一个自定义 UITableViewCell,我在其中使用 Interface Builder 连接了我的 UIButton
@IBOutlet var myButton: UIButton!
在 UITableViewController 的单元格配置下,我有以下代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var customCell = tableView.dequeueReusableCell(withIdentifier: self.MY_CELL_IDENTIFIER, for: indexPath) as! myCustomCell
// CONFIGURE OTHER CELL PARAMETERS
customCell.myButton.tag = indexPath.row
customCell.myButton.addTarget(self, action: #selector(myButtonPressed), for: UIControlEvents.touchUpInside)
return customCell
}
最后,我有
private func myButtonPressed(sender: UIButton!) {
let row = sender.tag
print("Button Sender row: \(row)")
}
此代码不起作用,除非我将函数定义更改为以下:
@objc private func myButtonPressed(sender: UIButton!) {
let row = sender.tag
print("Button Sender row: \(row)")
}
有没有更好的方法在 Swift 3 中的自定义 UITableViewCell 上实现 UIButton
【问题讨论】:
-
您是否尝试过从界面构建器创建操作?
-
放弃私有关键字
-
@LopesFigueiredo - 我没有创建 IBAction 的原因是因为会有多行,我必须检测按钮是从哪一行按下的。
-
每次重复使用一个单元格时,您都会为每个按钮添加目标。如果您不想在触摸按钮时多次调用 myButtonPressed 方法,则只需添加一次目标。
-
@LopesFigueiredo - 谢谢。我知道如何创建 IBAction,但是为了从行中唯一标识每个 UIButton,我尝试了上面详述的方法。