programmatically tap UIButton swift

8.7k views Asked by At

Direct Question:

How do you programmatically tap a UIButton in Swift 2.0?

Example: UIButton.tap()

Explanation as to why i cannot call button click function directly:

I am currently using AKSwiftSlideMenu (https://github.com/ashishkakkad8/AKSwiftSlideMenu) (https://www.cocoacontrols.com/controls/akswiftslidemenu) to create a menu. This is accomplished by adding the menu view controller to the main view controller as a child view.

let menuVC : BackTableViewController = self.storyboard!.instantiateViewControllerWithIdentifier("backTableViewController") as! BackTableViewController
    menuVC.btnMenu = sender

    self.view.addSubview(menuVC.view)
    self.addChildViewController(menuVC)

As you can see, the btnMenu, which is a UIButton, is being passed to the menuVC. Having the same button on both view controllers allows for a single onSlideMenuButtonPressed(sender : UIButton) function in the home view controller to handle the presentation of the menuVC. One of the options in the menu i am creating is the "Log out" button that presents a UIAlertViewController which ask if the user wants to sign out. The following is my code for my "Yes" button handler in the menuVC:

        logOutAlert.addAction(UIAlertAction(title:"Yes", style: .Default, handler:  { action in 
        self.btnMenu.touchInside
        CURRENT_USER.unauth()
        NSUserDefaults.standardUserDefaults().setValue(nil, forKey: "uid")
        print("User logged out")
        CurrentUser.checkIfUserIsLoggedIn()
    }))

I am attempting to tap the button with the touchInside method (which is not right of course) in order to dismiss the menuVC . Is there such thing as a UIButton.tap() equivalent or a way to access the btnMenu onSlideMenuButtonPressed(sender : UIButton) function?

Side Note: I played with the idea of creating a homeViewControllerDelegate object for the menuVC to call the onSlideMenuButtonPressed(sender : UIButton) directly, which might work, but it seems like a round about way seeing as the btnMenu already has a reference to that function.

2

There are 2 answers

2
Adrian Sluyters On BEST ANSWER

have you tried:

myAutomatedButton.sendActionsForControlEvents(.TouchUpInside)

This appears to be a previous question and a possible duplicate, but the post I found was: how to programmatically fake a touch event to a UIButton?

+1 for swift 3/4 below: @Eneko Alonso

0
Matt On

Also with @IBAction defined can just call it :

@IBAction func myButtonAction(_ sender: UIButton) {
    // do something
}

func otherMethod() {
   self.myButtonAction(UIButton())
}