无法在viewdidload上添加addsubview

lil*_*lzz 0 iphone

在UIViewController中,tempview2根本没有出现.只有tempview出现了.

        
-(id) init:(NSData*) imageData
{
    if ((self = [super init])) {    

    tempimage= [[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pic1" ofType:@"png"]] autorelease];
    tempview=[[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
        [tempview setImage:tempimage];
        [self.view addsubview tempview];
}
 return self;

}

    -(void) viewdidload{
       tempimage2= [[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pic2" ofType:@"png"]] autorelease];
    tempview2=[[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
        [tempview2 setImage:tempimage2];
        [self.view addsubview tempview2];

}

如果我这样做,那么一切都很好,

-(id) init:(NSData*) imageData
{
    if ((self = [super init])) {    

    tempimage= [[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pic1" ofType:@"png"]] autorelease];
    tempview=[[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
        [tempview setImage:tempimage];
        [self.view addsubview tempview];
        tempimage2= [[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pic2" ofType:@"png"]] autorelease];
    tempview2=[[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
        [tempview2 setImage:tempimage2];
        [self.view addsubview tempview2];
}
 return self;

}

MiK*_*iKL 6

这不是您的问题的直接答案,而是一般的viewcontroller初始化和视图加载的良好实践:

  1. 在init方法中,您应该只初始化与视图无关的ivars或其他类数据.否则就会破坏延迟加载的概念.在您查看控制器的init方法期间,视图尚不存在.
  2. 在viewDidLoad方法中,您应该执行视图设置.在此阶段,视图实际上已加载,是时候正确设置它.

因此,我建议您将视图设置调用移至viewDidLoad,并查看问题是否仍然存在.

祝好运.