访问awakeFromNib中的视图? [英] Accessing View in awakeFromNib?

查看:84
本文介绍了访问awakeFromNib中的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在awakeFromNib中设置UIImageView背景颜色(见下文)

I have been trying to set a UIImageView background color (see below) in awakeFromNib

[imageView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:1.0]];

当它不工作时,我意识到它可能是因为视图尚未加载,

When it did not work, I realised that its probably because the view has not loaded yet and I should move the color change to viewDidLoad.

我可以验证我是否有这个权利?

Can I just verify that I have this right?

gary

EDIT_002:

我刚刚开始一个新项目,开始。我设置视图与我一直做的一样。结果是控件确实在awakeFromNib中设置为(null)。这是我有:

I have just started a fresh project to check this from a clean start. I setup the view the same as I always do. The results are that the controls are indeed set to (null) in the awakeFromNib. Here is what I have:

CODE:

@interface iPhone_TEST_AwakeFromNibViewController : UIViewController {
    UILabel *myLabel;
    UIImageView *myView;
}
@property(nonatomic, retain)IBOutlet UILabel *myLabel;
@property(nonatomic, retain)IBOutlet UIImageView *myView;
@end

@synthesize myLabel;
@synthesize myView;

-(void)awakeFromNib {
    NSLog(@"awakeFromNib ...");
    NSLog(@"myLabel: %@", [myLabel class]);
    NSLog(@"myView : %@", [myView class]);
    //[myLabel setText:@"AWAKE"];
    [super awakeFromNib];

}

-(void)viewDidLoad {
    NSLog(@"viewDidLoad ...");
    NSLog(@"myLabel: %@", [myLabel class]);
    NSLog(@"myView : %@", [myView class]);
    //[myLabel setText:@"VIEW"];
    [super viewDidLoad];
}

OUTPUT:

awakeFromNib ...
myLabel: (null)
myView : (null)
viewDidLoad ...
myLabel: UILabel
myLabel: UIImageView



我会有兴趣知道这是否应该工作,从文档看起来像

I would be interested to know if this should work, from the docs it looks like it should, but given the way I usually set things up I can't quite understand why it does not in this case.

推荐答案

另一个答案:-)看起来你得到这种行为,因为控制器懒散地加载视图。视图不会立即加载,它会在第一次调用视图访问器时加载。因此,当您收到 awakeFromNib 时,NIB加载进程已完成,但不是为您的视图中的对象。请参阅此代码:

One more answer :-) It looks like you’re getting this behaviour because the controller loads the views lazily. The view is not loaded immediately, it gets loaded the first time somebody calls the view accessor. Therefore at the time you recieve awakeFromNib the NIB loading process is done, but not for the objects inside your views. See this code:

@property(retain) IBOutlet UILabel *foo;
@synthesize foo;

- (void) awakeFromNib
{
    NSLog(@"#1: %i", !!foo);
    [super awakeFromNib];
    NSLog(@"#2: %i", !!foo);
}

- (void) viewDidLoad
{
    NSLog(@"#3: %i", !!foo);
}

此日志:

#1: 0
#2: 0
#3: 1

但是如果你强制加载视图:

But if you force-load the view:

- (void) awakeFromNib
{
    [super awakeFromNib];
    [self view]; // forces view load
    NSLog(@"#1: %i", !!foo);
}

日志更改为:

#3: 1
#1: 1

这篇关于访问awakeFromNib中的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆