Home > Software design >  when changing the root viewcontroller my screen is going black
when changing the root viewcontroller my screen is going black

Time:12-27

So I am still learning swift and IOS. I guess there is a pretty simple answer to this, but for the love of god, I can't find it. I have spent some time now searching the net. Also the Open Ai chat, but nothing helps.

I have a login navigation setup, and if a user is logged in, I want to not show the login page again. I am using firebase auth for this.

When I am creating a new user, and they succesfully sign up, I want them to navigate to the main page of the app.

I have this code in the sign up viewcontroller.

signUp(onSucces: {
  // switch view
  let vc = MainViewController()
  self.navigationController?.setViewControllers([vc], animated: true)
}) { (errorMessage) in
  ProgressHUD.showError(errorMessage)
} 

and I have this in the new view controller I want to make root.

    override func viewDidLoad() {
        super.viewDidLoad()
    }

When the I succesfully sign up, the screen just go black. Also if I have a label, and I cahnge the text of the label in hte new viewcontroller, I get a weird error. I know this might be stupid little error, but I can't seem to find it, or know what to do. Please help.

CodePudding user response:

If you create a viewcontroller programmatically like you did

  let vc = MainViewController()
  self.navigationController?.setViewControllers([vc], animated: true)

The vc's background color is automatically will be black

To make change to it , in your MainViewController's viewDidLoad method , give a background color

  override func viewDidLoad() {
     super.viewDidLoad()
     self.view.backgroundColor = UIColor.white  //give desired color here
  }

CodePudding user response:

It is unclear from your question whether the view controller is StoryBoard based or not.

If it is, then you need to use instantiateViewController(withIdentifier identifier: String) in order to initialize the view controller, instead of a simple init which is what you do at the moment.

If it isn't storyboard based, then something is probably wrong with the view controller code, so it is recommended to post the entire code.

CodePudding user response:

What went wrong:

 let vc = MainViewController(). // this is just class object and will not present any UI or screen.

As per your code you are using UIKit and so to show any controller you have to instantiate the Storyboard controller like:

let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "myVCID")
self.navigationController?.setViewControllers([vc], animated: true)
  • Related