Presenting a view controller programmatically in swift

前端 未结 2 2026
挽巷
挽巷 2021-02-07 19:57

Hi I am trying to convert the following objective C code into swift to navigate from one view controller to another view controller when a button is clicked. any help would be m

2条回答
  •  暖寄归人
    2021-02-07 20:48

    Do you want to present navController modally?

    if yes, this is the answer

    self.presentViewController(navController, animated: true, completion: nil)
    

    "self" is the current view controller that will present the navController

    And put it like this,

    class ViewController: UIViewController {       
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            var theButton = UIButton()
    
            // Add the event to button
            theButton.addTarget(self, action: "buttonTouchInside:", forControlEvents: .TouchUpInside)
    
            self.view.addSubview(theButton)
        }
    
        func buttonTouchInside(sender:UIButton!)
        {
            // When the button is touched, we're going to present the view controller
    
            // 1. Wrap your view controller within the navigation controller
    
            let navController = UINavigationController(rootViewController: yourViewController)
    
            // 2. Present the navigation controller
    
            self.presentViewController(navController, animated: true, completion: nil)
        }
    
    }
    

    But,

    If you want to navigate between viewController in the navigationController, you can use

    self.navigationController.pushViewController(viewControllerToPush, animated: true)
    

提交回复
热议问题