Swift: How to press a button programmatically?

I have 2 view controllers that need to be replaced according to userinput. So, I want the program changes to switch based on the input that I get from the text file.

Algorithm : if(input == 1) { Go to View Controller 1 } else if(input ==2) { Go to View Controller 2 } 

any help on how to press a button programmatically or load this particular view controller using input !.

+7
swift
source share
2 answers

To programmatically fire an event, you need to call sendActionsForControlEvent

 button.sendActionsForControlEvents(.TouchUpInside) 

-

Swift 3

 button.sendActions(for: .touchUpInside) 
+37
source share

Or you can simply put all the logic that you execute when the button is clicked in a separate method and call that method from your button selection method.

 @IBAction func someButtonPressed(button: UIButton) { pushViewControllerOne() } @IBAction func someButtonPressed(button: UIButton) { pushViewControllerTwo() } func pushViewControllerOne() { let viewController = ViewControllerOne(nibName: "ViewControllerOne", bundle: nil) pushViewController(viewController) } func pushViewControllerTwo() { let viewController = ViewControllerOne(nibName: "ViewControllerTwo", bundle: nil) pushViewController(viewController) } func pushViewController(viewController: UIViewController) { navigationController?.pushViewController(viewController, animated: true) } 

Then, instead of calling the program call of the button, click, just call the pushViewControllerOne() or pushViewControllerTwo() method

+3
source share

All Articles