30

I have something like this:

myViewController = [[MyViewController alloc] initWithNibName:@"MyView" bundle:nil];
[mainCanvas addSubview: myViewController.view];
self.view = mainCanvas;

It will be added at the position (0, 0), but I want to add it at (0, 100) or somewhere else. How can I do so?

Pang
  • 9,564
  • 146
  • 81
  • 122
DNB5brims
  • 29,344
  • 50
  • 131
  • 195

4 Answers4

55

Something like this:

myViewController = [[MyViewController alloc] initWithNibName:@"MyView" bundle:nil];
myViewController.view.frame = CGRectMake(0, 100, myViewController.view.frame.size.width, myViewController.view.frame.size.height);  
[mainCanvas addSubview: myViewController.view];
self.view = mainCanvas;
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
acqu13sce
  • 3,789
  • 4
  • 25
  • 32
  • @applefreak the frame *is* the position of the view in its superview's co-ordinate system. What you're asking for doesn't make sense. – Mark Amery May 30 '15 at 01:46
  • This is the cleanest way and doesn't even require mask-translations to be enabled. Unbelievably, in my case, `(0, 0, width, height)` had to be declared explicitly as it wasn't default behaviour. Crazy! – Angad Jul 06 '16 at 18:30
12

In addition to setting the frame property, you can also set the center property of a view.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
8

Set the frame property on the sub view.

Gary
  • 5,642
  • 1
  • 21
  • 41
7

This is the best way I've found to add a subView, like a loading screen or something that you want to show whether you are in a UIView, UIScrollView, or UITableView.

myViewController = [[MyViewController alloc] initWithNibName:@"MyView" bundle:nil]; 
myViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.view addSubview:myViewController.view];
self.view.bounds = myViewController.view.bounds;

This will make the subView appear in full screen no matter where you are in the self.view by adding the subView to where you are currently located in your self.view instead of positioning it in the top left corner, only showing fully if you are at the very top of your view.

Dharmesh Dhorajiya
  • 3,976
  • 9
  • 30
  • 39
whyoz
  • 5,168
  • 47
  • 53