我有一个几乎只使用代码制作的用户界面:所有内容(用户界面标签等)都在 View Controller 的 viewdidload 中初始化。
.h
@interface homeViewController : UIViewController {
//IBOutlet UILabel *lbl; // not using an outlet anyway...
UILabel *lbl;
}
@property(nonatomic,retain) UILabel *lbl;
@end
.m
@interface homeViewController ()
@end
@implementation homeViewController
@synthesize lbl;
-(void)updateLabel {
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
double temptemp2 = [ud doubleForKey:@"somekey"];
lbl.text = [NSString stringWithFormat:@"%f", temptemp2];
[ud synchronize];
}
然后在 viewdidload 中调用 [self updateLabel];并且标签不会更新。但是,如果我将 updateLabel 方法中的相同代码放入 View 中确实加载,则该代码有效。
UIlabel 在 [self updateLabel] 之前被初始化(alloc init); View 内部确实加载了。
如果我不想使用界面构建器来初始化标签对象,我应该如何正确初始化它?以便可以从同一 View Controller 内的其他方法访问它?
最佳答案
您已经在 View Controller 上为标签创建了一个@property,但是当您创建标签时,您是将其分配给局部变量而不是属性。因此,当您想要分配值时,您以后无法通过其他方法引用它。
在您的 viewDidLoad
中,将您创建的 UILabel 对象分配给属性,如下所示:
self.lbl = lbl;
然后在您的 updateLabel
方法中:
self.lbl.text = [NSString stringWithFormat:@"%f", temptemp2];
关于ios - 除了 .storyboard(Outlet 引用)或 alloc int in view 之外的其他地方初始化的 UIlabels 是否加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11961507/