UIView的大小不是预期的

时间:2012-02-18 14:20:42

标签: objective-c ios uiview

我无法弄清楚为什么该视图会占据整个屏幕。

在AppDelegate文件中

...

self.viewController = [[[ViewController alloc]init]autorelease];
[self.window setRootViewController:self.viewController];
self.window.backgroundColor = [UIColor whiteColor];

...

在ViewController.m中

UIView *view = [[UIView alloc]initWithFrame:CGRectMake(30, 30, 30, 30)];
[view setBackgroundColor:[UIColor greenColor]];
self.view = view;

当我运行应用程序时,屏幕完全是绿色的,而不是只有绿色的正方形。 这有什么不对?

2 个答案:

答案 0 :(得分:5)

错误的一行在这里:

self.view = view;

当您设置作为根控制器的UIViewController的视图时,可以保证填满屏幕。相反,将其添加为子视图:

[self.view addSubview:view];

你应该没事。

答案 1 :(得分:0)

视图控制器会自动管理其根视图(self.view)的大小,因此即使您使用较小的大小初始化它,它也会稍后调整大小以填充屏幕。当界面方向改变时,也可以方便地调整大小(参见答案this question)。

根据Richard的回答,您可以将绿色视图作为子视图添加到控制器的根视图中。您获得的崩溃可能是因为当您尝试访问根视图时,根视图尚不存在。请尝试以下方法:

- (void) loadView
{
  [super loadView];  // creates the root view

  UIView* subView = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 30, 30)];
  [subView setBackgroundColor:[UIColor greenColor]];
  // because you don't set any autoresizingMask, subView will stay the same size

  [self.view addSubview:subView];
}