Ios 来自tableViewCell的swift@iAction

Ios 来自tableViewCell的swift@iAction,ios,swift4,ibaction,iboutlet,Ios,Swift4,Ibaction,Iboutlet,我需要通过单击tableViewCell触发一个函数, 到目前为止,我使用@iAction,但该选项仅适用于按钮类型(我还没有找到其他方法…) 这就是我现在的方式: @IBAction func springPrs(_ sender: Any) { //doing stuff.. } 但现在我有了一个@IBOutlet @IBOutlet weak var nextTrackCell: nextTableViewCell! 我想通过点击它来触发一个函数。有什么帮助吗?这是一种错误的

我需要通过单击tableViewCell触发一个函数, 到目前为止,我使用@iAction,但该选项仅适用于按钮类型(我还没有找到其他方法…) 这就是我现在的方式:

@IBAction func springPrs(_ sender: Any) {
    //doing stuff.. 
}
但现在我有了一个
@IBOutlet

@IBOutlet weak var nextTrackCell: nextTableViewCell!

我想通过点击它来触发一个函数。有什么帮助吗?

这是一种错误的方法,您应该从
UITableViewDelegate
实现一个名为
didSelectRowAt
的委托方法:

  public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          //do your stuff here.
        }
cell.onButtonPressed = { [unowned self] in
    // Do what you need to, no need to capture self however, if you won't access it.
}

您不应该将操作直接添加到表视图单元格中,因为它违反了MVC设计模式,而且
UITableViewDelegate
中已经内置了一个方便的回调函数,使之非常简单

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        // do something when the top row tapped
    } else {
        // do something when any other row is tapped
    }
}

您还可以在单元格内声明一个闭包,这是我在必须将某些操作传递给视图控制器时通常使用的方法

var onButtonPressed: (() -> ())?

@IBAction func buttonPressed(_ sender: Any) {
    onButtonPressed?()
}
并在
cellForRowAt
中这样使用:

  public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          //do your stuff here.
        }
cell.onButtonPressed = { [unowned self] in
    // Do what you need to, no need to capture self however, if you won't access it.
}

我认为override关键字会触发编译器错误。@LuizFernandoSalvaterra你说得对,我道歉。如果使用
UITableViewController
,委托回调已经实现,那么这就是代码。是的,我也使用这种方法,哈哈,谢谢,但问题是我在表视图外创建了一个单独的单元格,我是swift新手,我猜这不是正确的做法(我想知道其中的缺点),但还是有办法吗?是的,这是做你想做的事的正确方法。此外,不应在tableview外部创建单元格。单元格用于表格视图,而不是单独使用。如果您使用的是一个单元格,请考虑用UIVIEW切换它,我如何为UIVIEW创建一个“OnCutle”函数?这个答案将帮助您: