Giovanni Grano Giovanni Grano - 5 months ago 32
iOS Question

#selector on UIBarButtonItem

I'm developing my first iOS app in Swift 2.2 and I have the following problem.
In an utility class, I have the following static method, called by some different

UIViewController
.

static func setNavigationControllerStatusBar(myView: UIViewController, title: String, color: CIColor, style: UIBarStyle) {
let navigation = myView.navigationController!
navigation.navigationBar.barStyle = style
navigation.navigationBar.barTintColor = UIColor(CIColor: color)
navigation.navigationBar.translucent = false
navigation.navigationBar.tintColor = UIColor.whiteColor()
myView.navigationItem.title = title

let menuButton = UIBarButtonItem(image: UIImage(named: "menu"),
style: UIBarButtonItemStyle.Plain ,
target: self, action: #selector("Utils.menuClicked(_:)"))

myView.navigationItem.leftBarButtonItem = menuButton
}

func menuClicked(sender: UIButton!) {
// do stuff
}


I'm trying in some different ways to associate a
#selector
for this button, however I always have the following error.

enter image description here

Answer

No quotes.

#selector(Utils.menuClicked(_:))

func menuClicked should be in your view controller class. But if for some reason it isn't, you can do

class Utils {
    static let instance = Utils()

    let menuButton = UIBarButtonItem(image: UIImage(named: "menu"),
                                     style: UIBarButtonItemStyle.Plain ,
                                     target: Utils.instance, action: #selector(Utils.menuClicked(_:)))

    @objc func menuClicked(sender: UIBarButtonItem) {
        // do stuff
    }
}
Comments