Search code examples
iosuibarbuttonitemswift2unrecognized-selector

Swift - Call a function when button is pressed - unrecognized selector sent to instance


I'm programmatically adding some buttons to my toolbar using swift. I've seen how to add an action to a button and I think I'm doing it correctly, but obviously I'm not because I keep getting "unrecognized selector sent to instance" when I press the button. What am I doing wrong?

Here's how I'm adding the buttons to the toolbar:

func addButtonsToToolbar(view: UIView?)
{
    let userTrackingArrow = MKUserTrackingBarButtonItem(mapView: self.mapView)
    let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    let refresh: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: view, action: "refreshbuttonTapped:")

    var items = [UIBarButtonItem]()
    items.append(userTrackingArrow)
    items.append(flexSpace)
    items.append(refresh)

    self.toolBar.items = items
}

This is the function I want called with the "refresh" button is pressed, but it's not being called. Instead I get "unrecognized selector sent to instance".

func refreshbuttonTapped(sender: AnyObject!)
{
    print("Button tapped")
}

Solution

  • Try to change target of refresh button:

    let refresh: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: view, action: "refreshbuttonTapped:")
    

    to:

    let refresh: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "refreshbuttonTapped:")