0

I need to trigger a function by clicking on a tableViewCell, until now I used @IBAction, but that option is only available with button type (I haven't found another way..) this is the way I now of:

@IBAction func springPrs(_ sender: Any) {
    //doing stuff.. 
}

but now I have an @IBOutlet

@IBOutlet weak var nextTrackCell: nextTableViewCell!

and I want to trigger a function by clicking on it. Any help?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Nadav
  • 333
  • 3
  • 16

3 Answers3

1

This is a wrong approach, you should implement a delegate method from UITableViewDelegate called didSelectRowAt:

  public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          //do your stuff here.
        }
Luiz Fernando Salvaterra
  • 4,192
  • 2
  • 24
  • 42
  • thanks, but the thing is I created a singe cell outside of a table view, I'm new in swift, I'm guessing it's not the right thing to do(i'd like to know the disadvantages in this), but still, is there a way? – Nadav Oct 19 '17 at 11:18
  • Is, this is the right way to do what you want. Also, you should not create a cell outside a tableview. cells are made for use with a tableview, not alone. If you are using a single cell, consider switching it by a UIView instead – Luiz Fernando Salvaterra Oct 19 '17 at 11:27
  • and how can I create an "onclick" function for UIview? – Nadav Oct 19 '17 at 12:15
  • this answer will help you : https://stackoverflow.com/questions/30505165/swift-uiview-touch-event-in-controller – Luiz Fernando Salvaterra Oct 19 '17 at 12:22
0

You shouldn't add an action directly to a table view cell because it violates the MVC design pattern and there is a handy callback already built into UITableViewDelegate to make this really easy.

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
    }
}
Bradley Mackey
  • 6,777
  • 5
  • 31
  • 45
0

You could also declare a closure inside the cell, this is what I tend to use when having to pass some action to the view controller.

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

@IBAction func buttonPressed(_ sender: Any) {
    onButtonPressed?()
}

And use it like so in cellForRowAt:

cell.onButtonPressed = { [unowned self] in
    // Do what you need to, no need to capture self however, if you won't access it.
}
Balázs Vincze
  • 3,550
  • 5
  • 29
  • 60