Swift - 按下按钮时调用函数 - 无法识别的选择器发送到实例

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

我正在使用 swift 以编程方式向我的工具栏添加一些按钮。我已经看到了如何向按钮添加操作,我认为我做的是正确的,但显然我不是,因为当我按下按钮时我一直得到 "unrecognized selector sent to instance"。我做错了什么?

以下是我将按钮添加到工具栏的方法:

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
}

这是我想要在按下 "refresh" 按钮时调用的函数,但它没有被调用。相反,我得到 "unrecognized selector sent to instance".

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

方法refreshbuttonTapped()必须在targetclass中实现,也就是在addButtonsToToolbar()

中作为参数传递的view

尝试更改刷新按钮的目标:

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

至:

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