Objective c UIView大小不是预期的大小

Objective c UIView大小不是预期的大小,objective-c,ios,uiview,Objective C,Ios,Uiview,我不明白为什么这个视图占据了整个屏幕 在AppDelegate文件中 在ViewController.m中 UIView *view = [[UIView alloc]initWithFrame:CGRectMake(30, 30, 30, 30)]; [view setBackgroundColor:[UIColor greenColor]]; self.view = view; 当我运行应用程序时,屏幕是完全绿色的,而不是只有一个绿色的正方形。 这里怎么了?错误的行在这里: self.

我不明白为什么这个视图占据了整个屏幕

在AppDelegate文件中

在ViewController.m中

UIView *view = [[UIView alloc]initWithFrame:CGRectMake(30, 30, 30, 30)];
[view setBackgroundColor:[UIColor greenColor]];
self.view = view;
当我运行应用程序时,屏幕是完全绿色的,而不是只有一个绿色的正方形。
这里怎么了?

错误的行在这里:

self.view = view;
当您设置作为根控制器的
UIViewController
视图时,它保证填充屏幕。而是将其添加为子视图:

[self.view addSubview:view];

您应该会没事。

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

根据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];
}

你把self.view=view设置在哪里?我不明白你问什么。你把第二段代码放在哪里?在
loadView
方法中?但正如Richard J.Ross III所建议的,也许您需要使用(例如)
[self.window addSubview:view]它位于loadView方法中。我尝试使用[self.window addSubview]但当我更改为[self.view addSubview:view]时,应用程序崩溃,gdb打印“无法恢复以前选择的帧”消息。我在gdb中遇到“无法恢复以前选择的帧”错误
- (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];
}