38

I have 2 view controllers which should be swapped according to userinput. So, I want to switch the views programatically based on the input I get from a 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 click the button programmatically or load that particular viewcontroller with input?

Shawn Frank
  • 4,381
  • 2
  • 19
  • 29
Coding4Life
  • 619
  • 2
  • 7
  • 14

2 Answers2

140

To fire an event programmatically you need to call sendActionsForControlEvent

button.sendActionsForControlEvents(.TouchUpInside)

--

Swift 3

button.sendActions(for: .touchUpInside)
Community
  • 1
  • 1
Adnan Aftab
  • 14,377
  • 4
  • 45
  • 54
0

Or you can just put all the logic that you perform when a button gets clicked in a separate method, and call that method from your button's selector 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 invoking programatically invoking a button press, just call the method pushViewControllerOne() or pushViewControllerTwo()

Sajjon
  • 8,938
  • 5
  • 60
  • 94
  • 1
    no, that's not what the original poster was asking. – spnkr Jul 19 '19 at 05:55
  • 4
    Well, sometimes one has to read between the lines of what OP wants to achieve. It is often the case where (s)he does not know about a better way of reaching the end goal... – Sajjon Jul 19 '19 at 15:16
  • 2
    yes i agree Sajjon, good point, i didn't mean to be so terse, my bad. in this case i think that `button.sendActions(for: .touchUpInside)` is the right answer, but your solution is also valid. – spnkr Jul 26 '19 at 00:34