以编程方式更改 viewDidLoad() 中 UILabel 的文本
如何在视图控制器的 viewDidLoad 方法中更改 UILabel 的文本?
我下面的代码不会更新用户界面。
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil
bundle:nibBundleOrNil]) {
displayLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 20, 230, 40)];
[self.view addSubview:displayLabel];
}
return self;
}
//
- (void)viewDidLoad {
[super viewDidLoad];
displayLabel.text = @"abc";
}
How do I change the text of my UILabel in viewDidLoad method of my view controller?.
My code below does not update the UI.
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil
bundle:nibBundleOrNil]) {
displayLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 20, 230, 40)];
[self.view addSubview:displayLabel];
}
return self;
}
//
- (void)viewDidLoad {
[super viewDidLoad];
displayLabel.text = @"abc";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该尝试在 viewDidLoad 中添加子视图。
self.view 是一个 IBOutlet,在调用 initWithNibName 时它不会被加载到内存中,并且将等于 nil。
viewDidLoad 在视图控制器将其关联的视图加载到内存后被调用。因此 self.view 将指向您在 nib 文件中创建的视图。
You should try adding the subview in viewDidLoad.
self.view is an IBOutlet and it will not be loaded into memory at the point that initWithNibName is called, and will be equal to nil.
viewDidLoad is called after the view controller has loaded its associated views into memory. And as such self.view will point to the view you created in your nib file.