0

I'm struggling to find a way to pass parameter using the #selector. I've gone over some similar questions however keep getting similar errors. Can someone explain how to do this properly please? I need to get the urlString to print however I get the following error:

Argument of '#selector' does not refer to an '@objc' method, property, or initializer

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! SearchiTunesResultCell
    let song = songs[indexPath.item]
    cell.song = song
    cell.songTitle.text = "Song: \(song.trackName ?? "")"
    cell.artistName.text = "Artist: \(song.artistName ?? "")"
    cell.albumName.text = "Album: \(song.collectionName ?? "")"
    cell.playPauseButton.addTarget(self, action: #selector(handlePlayPreview(url: song.previewUrl!)), for: .touchUpInside)
    return cell
}

@objc func handlePlayPreview(url: String)  {
    print("playing URL:", url)
}
unicorn_surprise
  • 951
  • 2
  • 21
  • 40
  • 1
    Short answer, you can't pass arbitrary values. Long answer, you don't need to. Use a different approach. See https://stackoverflow.com/questions/28659845/swift-how-to-get-the-indexpath-row-when-a-button-in-a-cell-is-tapped/38941510#38941510 – Paulw11 Jul 22 '19 at 00:27

1 Answers1

2

Create a custom button. I have added only URL property. You can add more. set this custom button type in your storyboard against your playPauseButton. Also, replace the existing playPauseButton property with a new one.

class CustomButton: UIButton {
    var url:String? = nil
}



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! SearchiTunesResultCell
    let song = songs[indexPath.item]
    cell.song = song
    cell.songTitle.text = "Song: \(song.trackName ?? "")"
    cell.artistName.text = "Artist: \(song.artistName ?? "")"
    cell.albumName.text = "Album: \(song.collectionName ?? "")"
    if let url = song.previewUrl {
        cell.playPauseButton.url = url
    }
    cell.playPauseButton.addTarget(self, action: #selector(handlePlayPreview(sender:)), for: .touchUpInside)
    return cell
}



@IBAction func (sender: CustomButton) {
    print("playing URL:", sender.url)
}
Animesh
  • 497
  • 5
  • 17