-1

to sum up my problem: I have a bigger table with lots of posts from different people. And I am going through my list of tablecells with the datasource of the tableview like in the following example. And I want to give each textlabel of the cell a click listener. So I came up with this here in my cellForRowAt at my tables datasource:

    let tap = UITapGestureRecognizer(target: self, action: #selector(clickedOnLabel(sender:, content: local[indexPath.row][2],rank: rank)))
    cell.textLabel?.isUserInteractionEnabled = true
    cell.addGestureRecognizer(tap)

So I wanna add this click funktion right here, which needs the arguments content and rank with it:

@objc func clickedOnLabel(sender: UITapGestureRecognizer, content: String, rank: Int){

    //Do some stuff here

}

But I am not allowed to pass content and rank with the selector, when I put content and rank out, everything works fine... So is it just syntax?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
CaipiDE
  • 93
  • 1
  • 10

2 Answers2

0

Here is a small example of how you can achieve this by using closures.

cell.updateParent = { [weak self] score, rank in
    // Do magic here
}

And in your cell class you should add something like

var updateParent: ((Double, Int) -> Void)?

@IBAction func doMagicInParent(_ sender: Any) {
    updateParent?(score, rank)
}

This can be achieved by using delegates as well. Or you can also pass the data through the notification center.

Notification center example

Delegate example

Savca Marin
  • 427
  • 4
  • 11
0

Here's a solution using delegate:

In your custom cell

protocol MyCustomCellDelegate{
    func didTapOnLabel(content: String, rank: Int)
}

var delegate: MyCustomCellDelegate?

When tap happens, call

self.delegate?.didTapOnLabel(content: "my content", rank: 100)

In your CellForRowAt Function

cell.delegate = self

and conform the delegate:

extension YouViewController: MyCustomCellDelegate{
    func didTapOnLabel(content: String, rank: Int){
        // do your stuff
    }
}
Eray Alparslan
  • 806
  • 7
  • 12
  • But how am I supposed to know what to fill in my content and rank at your "When tap happens, call" because I cant pass my the objectivec function? And also I cant give my cell a delegate... – CaipiDE Oct 29 '19 at 16:22
  • Here is one more question, how are we supposed to know that you can't pass your objective-c function when you did not even mention this in the original question? – Savca Marin Oct 29 '19 at 16:27
  • @CaipiDE you need to trigger the delegate function in the objective c function implementation. Also I showed how to make delegation for your cell. Please read the instructions well. – Eray Alparslan Oct 29 '19 at 18:47