user3703539 user3703539 - 7 months ago 49
Swift Question

UIButton selector not work

I can't call buttonAction method, when i click nothing happen. I used the last #selector of swift 2.2 and my

buttonAction
function is already outside
notificationAlert
function.

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")
}
}

Answer

Change your AlertHelper class as follows and make that a singleton 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")

    }

}

Now in your other controller you can all as follows:

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

And you are done. Click will work!

Comments