How to click a button programmatically?

前端 未结 2 1138
梦毁少年i
梦毁少年i 2020-12-23 17:17

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.



        
相关标签:
2条回答
  • 2020-12-23 17:32

    To fire an event programmatically you need to call sendActionsForControlEvent

    button.sendActionsForControlEvents(.TouchUpInside)
    

    --

    Swift 3

    button.sendActions(for: .touchUpInside)
    
    0 讨论(0)
  • 2020-12-23 17:44

    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()

    0 讨论(0)
提交回复
热议问题