问题
Hi, I am coding an application on Xcode for IOS and I would like to send a variable to another ViewController. The problem is that when I want to send from the controller called "Step1" to set the label of my second view controller called "Step2". To do this I proceed in this way in "Step 1":
guard let step2 = self.storyboard?.instantiateViewController(withIdentifier: Step2) as? EndConfiguration else
{
fatalError("Error when trying to get the reference to the Step 2")
}
step2.nameLabelOutlet?.text = "Jonh"
But my label is not set... Could someone help me with this problem?
Thank you in advance.
回答1:
EDITED:
There are 3 parts to debugging the problem:
Does the call to
instantiateViewController(withIdentifier:)
return a viewController? As @aheze points out, you're passing an identifier ofEndConfiguration
. Unless that is a string constant (e.g.let EndConfiguration = "EndConfiguration"
) that seems odd. Since you're trying to cast the returned object to typeEndConfiguration
it seems clear that something isn't right. (EndConfiguration
can't be both a view controller class and a string constant.)
To debug the call toinstantiateViewController(withIdentifier:)
you should get rid of the cast (theas? EndConfiguration
bit) and see if the call returns a view controller.The second part is the conditional cast (The
as? EndConfiguration
bit.) If what is created is not a view controller of classEndConfiguration
that will fail. It's pretty easy to accidentally leave your view controller's class as the default classUIViewController
, and not change it to your custom class in Interface builder. To check that open your storyboard, select the scene for that view controller, select the view controller in that scene, and check in the "identity inspector" that the class is yourEndConfiguration
class.As pointed out by PaulW in his comment, a view controller's views are not loaded by the time it's returned in a call to
instantiateViewController(withIdentifier:)
, so your codestep2.nameLabelOutlet?.text = "Jonh"
won't work because nameLabelOutlet will be nil. Plus, you shouldn't manipulate another view controller's views. Treat them as private. You should add a string property to the target view controller that IT picks up in viewWillAppear and installs in it's view as appropriate.
来源:https://stackoverflow.com/questions/65256352/why-are-my-variables-empty-when-i-cast-them-in-my-ios-application