richc richc - 1 month ago 17
Swift Question

What is the action for custom accessory view button - swift

This seems to have been asked a few times in swift and objc, but I can't see a correct answer for swift so hopefully someone can help me this time. I have created a custom accessory view button, but need the correct button action: as "accessoryButtonTapped" is an unrecognised selector.

What is the selector needed to call the tableViewCellDelegate method willSelectRowAtIndexPath?

The code I have is:

let cellAudioButton = UIButton(type: .Custom)
cellAudioButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
cellAudioButton.addTarget(self, action: "accessoryButtonTapped", forControlEvents: .TouchUpInside) //INCORRECT ACTION:
cellAudioButton.setImage(UIImage(named: "blueSpeaker.png"), forState: .Normal)
cellAudioButton.contentMode = .ScaleAspectFit
cell.accessoryView = cellAudioButton as UIView


Thanks in advance to anyone who can help.

Answer

Why do you need to call willSelectRowAtIndexPath? You have done everything right and to solve your unrecognized selector error just make a function that will be called when you tap on the cell.accessoryView. In your case:

func accessoryButtonTapped(){
    print("Tapped")
}

Update
If you want to get the indexPath you could just

Add a tag to your cellAudioButton:

cellAudioButton.tag = indexPath.row

In your addTarget add a : to pass a parameter

And in your function

func accessoryButtonTapped(sender : AnyObject){
        print(sender.tag)
        print("Tapped")
    }

So the whole code:

let cellAudioButton = UIButton(type: .Custom)
        cellAudioButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
        cellAudioButton.addTarget(self, action: "accessoryButtonTapped:", forControlEvents: .TouchUpInside)
        cellAudioButton.setImage(UIImage(named: "blueSpeaker.png"), forState: .Normal)
        cellAudioButton.contentMode = .ScaleAspectFit
        cellAudioButton.tag = indexPath.row
        cell.accessoryView = cellAudioButton as UIView

func accessoryButtonTapped(sender : AnyObject){
        print(sender.tag)
        print("Tapped")
    }
Comments