Swift – Instantiating a navigation controller without storyboards in App Delegate

前端 未结 2 594
余生分开走
余生分开走 2020-12-04 16:48

I\'m rebuilding an app without storyboards and the part of it that I\'m having the most trouble with is navigating view-to-view programatically. Few things are written out t

相关标签:
2条回答
  • 2020-12-04 17:14

    In AppDelegate

    var window: UIWindow?
    var navController: UINavigationController?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
        navController = UINavigationController()
        var viewController: ViewController = ViewController()
        self.navController!.pushViewController(viewController, animated: false)
    
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    
        self.window!.rootViewController = navController
    
        self.window!.backgroundColor = UIColor.whiteColor()
    
        self.window!.makeKeyAndVisible()
    
        return true
    }
    

    In ViewController

    class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "FirstVC"
    
        var startFinishButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
        startFinishButton.frame = CGRectMake(100, 100, 100, 50)
        startFinishButton.backgroundColor = UIColor.greenColor()
        startFinishButton.setTitle("Test Button", forState: UIControlState.Normal)
        startFinishButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    
        self.view.addSubview(startFinishButton)
    }
    
    func buttonAction(sender:UIButton!)
    {
        println("Button tapped")
        let vc = SecondViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    }
    
    0 讨论(0)
  • 2020-12-04 17:31

    In Swift 3

    Place this code inside didFinishLaunchingWithOptions method in AppDelegate class.

    window = UIWindow(frame: UIScreen.main.bounds)
    let mainController = MainViewController() as UIViewController
    let navigationController = UINavigationController(rootViewController: mainController)
    navigationController.navigationBar.isTranslucent = false
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()
    
    0 讨论(0)
提交回复
热议问题