无法在viewdidload上添加addsubview

时间:2011-04-26 18:01:07

标签: 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;

}

2 个答案:

答案 0 :(得分:6)

这不是你问题的直接答案,而是一般的viewcontroller初始化和视图加载的好习惯:

  1. 在init方法中,您应该只初始化与视图无关的ivars或其他类数据。否则就会破坏延迟加载的概念。在您查看控制器的init方法期间,视图尚不存在。
  2. 在viewDidLoad方法中,您应该执行视图设置。在这个阶段,视图实际上已加载,是时候正确设置了它。
  3. 我建议您将视图设置调用移到viewDidLoad中,看看问题是否仍然存在。

    祝你好运。

答案 1 :(得分:0)

我同意MiKL。

但是无论如何回到你的问题你忘了打电话给[super viewDidLoad]?也许这就是问题所在?

此外,作为最佳做法,在将视图作为子视图添加到其他视图后释放视图(将视图作为子视图添加到另一个视图会增加其保留计数)。