【问题标题】:Having trouble to addsubview on viewdidload无法在 viewdidload 上添加子视图
【发布时间】:2011-08-13 06:17:10
【问题描述】:

在 UIViewController 内部,tempview2 根本没有出现。只有 tempview 出现。

-(id)初始化:(NSData *)图像数据 { 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]; [临时视图集图像:临时图像]; [self.view addsubview tempview]; } 回归自我; } -(无效)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)初始化:(NSData *)图像数据 { 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]; [临时视图集图像:临时图像]; [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]; } 回归自我; }

【问题讨论】:

    标签: iphone


    【解决方案1】:

    这不是对您问题的直接回答,而是视图控制器初始化和视图加载的一般做法:

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

    因此,我鼓励您将视图设置调用移到 viewDidLoad 中,看看问题是否仍然存在。

    祝你好运。

    【讨论】:

    • 好的,我将所有内容移至 viewdidload。发生的事情是 -(id) init:(NSData*) imageData 我从外部获取图像数据并显示出来。我先将图像数据保存到磁盘,然后将其带到 viewdidload 上查看。最好不要在 init 例程中设置视图。
    • 调用@siddharth Iyer 提到的[super viewDidLoad]。这很可能是您的问题的原因。感谢您的投票。
    【解决方案2】:

    我同意 MiKL。

    但无论如何,回到您的问题,您是否忘记调用 [super viewDidLoad]?也许这就是这里的问题?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多