問題描述
添加子視圖控制器並更改其標籤 (Adding a child view controller and changing its label)
I got a view controller named IntroViewController in my storyboard and I want to add this as a child to another view controller like this:
IntroViewController *introViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"View1"];
[introViewController.textLabel setText:@"test"];
[self addChildViewController:introViewController];
On the IntroViewController I've put a label named textLabel on it in the storyboard, if I run the program it works and shows me the view controller, but the text doesn't get changed. Any idea how I can fix this?
‑‑‑‑‑
參考解法
方法 1:
When you instantiate a view controller from a storyboard, the view is not loaded until it is actually presented on screen. At the point in your code you have posted introViewController.textLabel
is nil.
One option you could do is add a property to your IntroViewController
class and instead set that:
introViewController.initialText = @"test";
Then, inside ‑viewDidLoad
of your IntroViewController
the label will be instantiated so you can make the call:
[self.textLabel setText:self.initialText];
It is also worth noting that most of the time it would be recommended to have a view controller be the one to set values on the views it owns, rather than some other view controller.
(by user2117204、Simon Goldeen)