OhDoh
OhDoh

Reputation: 433

UIView size is not as expected to be

I can't figure out why that view takes the entire screen.

In AppDelegate file

...

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

..

In ViewController.m

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

When I run the app the screen is entirely green instead of having just a square in green. What is wrong here ?

Upvotes: 2

Views: 186

Answers (2)

herzbube
herzbube

Reputation: 13378

The view controller automatically manages the size of its root view (self.view), so even if you initialize it with a smaller size it will later get resized to fill the screen. This resizing conveniently also happens when the interface orientation changes (see the answer this question).

As suggested by Richard's answer, you can add your green view as a subview to the controller's root view. The crash you get is probably because the root view does not exist yet when you try to access it. Try the following:

- (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];
}

Upvotes: 0

Richard J. Ross III
Richard J. Ross III

Reputation: 55583

The erroneous line is here:

self.view = view;

When you set a view of a UIViewController that is the root controller, it is guaranteed to fill the screen. Instead, add it as a subview:

[self.view addSubview:view];

And you should be fine.

Upvotes: 5

Related Questions