2012-02-18 52 views
2

我無法弄清楚爲什麼這個視圖佔據了整個屏幕。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; 

當我運行應用程序的屏幕完全是綠色的,而不是隻有一個綠色的正方形。 這裏有什麼問題?

+0

您在哪裏設置'self.view = view'? – 2012-02-18 14:22:51

+0

我不明白你問什麼。 – OhDoh 2012-02-18 14:28:37

+0

你在哪裏第二段代碼?在'loadView'方法中?但正如Richard J. Ross III所建議的,也許你需要使用(例如)'[self.window addSubview:view];' – 2012-02-18 14:33:20

回答

5

錯誤路線是在這裏:

self.view = view; 

如果設置了UIViewController即根控制器的視圖,它是保證充滿整個屏幕。相反,將其添加爲子視圖:

[self.view addSubview:view]; 

而且你應該沒問題。

+0

當我更改爲[self.view addSubview:查看]應用程序崩潰,我得到「無法恢復先前選擇框架「錯誤在gdb – OhDoh 2012-02-18 14:28:13

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]; 
} 
相關問題