2016-06-21 61 views
0

我正在Swift 2.2中开发我的第一个iOS应用程序,并且遇到以下问题。 在实用程序类中,我有以下静态方法,由一些不同的UIViewController调用。UIBarButtonItem上的#selector

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 
} 

我想在一些不同的方式为这个按钮#selector关联,但是我总是有以下错误。

enter image description here

+3

尝试不引用它。 – zneak

回答

1

没有引号。

#selector(Utils.menuClicked(_:)) 

func menuClicked应该在你的视图控制器类中。但是,如果由于某种原因,它不是,你可以做

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 
    } 
} 
+0

我删除了引号,我没有编译错误。但是,触摸按钮,应用程序崩溃时出现以下消息“MyUnimol.Utils”未实现methodSignatureForSelector: - 前面的问题 无法识别的选择器+ [MyUnimol.Utils menuClicked]' –

+0

@GiovanniGrano实用程序类中的menuClicked函数或视图控制器类? – Code

+0

它与上述方法 –

1

Swift 2.2 deprecates using strings for selectors and instead introduces new syntax: #selector. Using #selector will check your code at compile time to make sure the method you want to call actually exists. Even better, if the method doesn’t exist, you’ll get a compile error: Xcode will refuse to build your app, thus banishing to oblivion another possible source of bugs.

所以移除你的方法双引号中#selector。它应该工作!