当我单击时,什么也没发生,所以我无法调用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 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)


您完成了。点击即可使用!

10-04 20:03