UIButton 选择器不起作用

UIButton selector not work

我无法调用 buttonAction 方法,当我点击时没有任何反应。我使用了 swift 2.2 的最后一个 #selector 并且我的 buttonAction 函数已经在 notificationAlert 函数之外。

class AlertHelper: UIViewController {

    var cancel_button: UIButton!

    func notificationAlert(message:String, viewController : UIViewController, color: UIColor) {

        cancel_button = UIButton(
            frame: CGRect(
                x: viewController.view.center.x,
                y: viewController.view.center.y + 50,
                width: 100,
                height: 50
            )
        )

        //Bind Click on Button ERROR
        cancel_button.addTarget(self, action: #selector(AlertHelper.buttonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)

        viewController.view.addSubview(cancel_button)

    }

    class func displayError(message:String, viewController : UIViewController) {
        AlertHelper().notificationAlert(message, viewController: viewController, color : .whiteColor())
    }

    func buttonAction(sender: UIButton!)
    {
       print("ok")
    }
}

如下更改您的 AlertHelper class 并使其成为单例 class

class AlertHelper: UIViewController {

    var cancel_button: UIButton!

    // Here is your static object that will always remain in memory
    static let sharedInstance = AlertHelper()

    func notificationAlert(message:String, viewController : UIViewController, color: UIColor) {

        cancel_button = UIButton(
            frame: CGRect(
                x: viewController.view.center.x,
                y: viewController.view.center.y + 50,
                width: 100,
                height: 50
            )
        )

        //Bind Click on Button ERROR
        cancel_button.addTarget(self, action: #selector(AlertHelper.buttonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)

        viewController.view.addSubview(cancel_button)

    }

    func displayError(message:String, viewController : UIViewController) {
        //Maintaining the same static object and not making any new object
        AlertHelper.sharedInstance.notificationAlert(message, viewController: viewController, color : .whiteColor())
    }

    func buttonAction(sender: UIButton!) {

    print("ok")

    }

}

现在在你的另一个控制器中你可以全部如下:

AlertHelper.sharedInstance.displayError("Check", viewController: self)

大功告成。点击即可!