我有一个名为TimerViewController
的自定义视图控制器,它的子类称为FirstViewController
和FourthViewController
。
我在FirstViewController
的.
h中声明了一个名为controller
的FirstViewController
实例。
在FourthViewController
的.m
的viewDidLoad
方法中,我有:
controller = [self.storyboard instantiateViewControllerWithIdentifier:@"mainController"];
在故事板中,我已经将视图控制器ID声明为mainController
,并声明了FourthViewController
的自定义类。然后,在FourthViewController
的.m
中,我有:
controller.mainLab.text = [NSMutableString stringWithFormat:@"This is a string"];
NSLog(@"%@", controller.mainLab.text);
然而,这会输出(null)
。
为什么会发生这种情况?
mainLab
必须是nil
。所以你的插座可能没有连接到你的XIB。
顺便说一句,将stringWithFormat:
与非格式的字符串一起使用是浪费。
你忽略了告诉我们关于你项目其余部分的一些信息,我只是不确定它是什么。
我启动了Xcode,只是为了快速运行,过程很简单。
将UI标签拖动到XIB
控制从标签到.h 的点击
为了测试,我做了
#import "SOViewController.h"
- (void)viewDidLoad
{
[super viewDidLoad];
self.mainLabel.text = @"This is my label";
NSLog(@"%@", self.mainLabel.text);
}
我的.h看起来像这样:
#import <UIKit/UIKit.h>
@interface SOViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *mainLabel;
@end
这是自定义类的一部分吗?还有别的事吗?如果它是一个香草标签,那么使用上述代码应该可以正常工作。
您的mainLab
似乎尚未创建。当您对nil对象调用方法时,该方法会自动返回nil。在运行这行代码之前,请确保您确实创建了标签。
您不能在实例化另一个控制器后立即访问它的标签(或任何其他UI元素),因为它的viewDidLoad方法尚未运行。如果你想在另一个控制器中设置标签的文本,你必须将文本传递给该控制器,并让它在其viewDidLoad方法中设置标签上的文本。所以取而代之的是:
controller = [self.storyboard instantiateViewControllerWithIdentifier:@"mainController"];
controller.mainLab.text = [NSMutableString stringWithFormat:@"This is a string"];
你需要这样做:
controller = [self.storyboard instantiateViewControllerWithIdentifier:@"mainController"];
controller.mainLabText = @"This is a string";
其中mainLabText是在FourthViewController中创建的字符串属性。然后在FourthViewController的视图DidLoad:中填充标签
self.mainLab.text = self.mainLabText;