2

I have a collection view and image view inside it and I added a UIButton to delete the image after selection. When I click the button it crashes and gives me this error:

AdPostViewController deleteUser]: unrecognized selector sent to instance 0x7fb588d5b7f0

Why is this happening and how do I fix this? Here is my code:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
    
    let img = self.PhotoArray[indexPath.row]
    cell.image.image = img
    
    cell.deleteButton?.layer.setValue(indexPath.row, forKey: "index")
    cell.deleteButton?.addTarget(self, action: Selector(("deleteUser")), for: UIControl.Event.touchUpInside)
    
    return cell
}

func deleteUser(_ sender: UIButton) {
    let i: Int = (sender.layer.value(forKey: "index")) as! Int
    PhotoArray.remove(at: i)
    // PhotoArray.removeAtIndex(i)
    ImagesCollectionView.reloadData()
}
TylerP
  • 9,600
  • 4
  • 39
  • 43
Jacob
  • 121
  • 1
  • 8

1 Answers1

3

One problem is that you are forcing manual formation of the Objective-C selector, and you don't actually know how to form an Objective-C selector manually so you are getting it wrong. Don't do that! Let the compiler form the selector for you. That's its job. Replace

action: Selector(("deleteUser"))

with

action: #selector(deleteUser)

Also, you need to expose your deleteUser method to Objective-C explicitly:

@objc func deleteUser(_ sender: UIButton) {

Otherwise Objective-C still won't be able to introspect your class and find this method when the time comes to call it. Fortunately, when you switch to #selector syntax, the compiler will call out that issue for you!

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 2
    Shouldn't that be `#selector(deleteUser(_:))` since his selector has an anonymous parameter? – Duncan C Jan 22 '21 at 20:07
  • 1
    @DuncanC No, there is no ambiguity so the base name will work fine as a reference to this function. That is the joy of `#selector`. It thinks so you don't have to. – matt Jan 22 '21 at 20:08