I need to make sure that one view A (size: 200x200) is always aligned to top right corner inside second view B (full screen size). I want to make sure that view A stays in that place regardless of device orientation. Truth is I have no problem with this when using interface builder to position the views but I need to construct this programmatically. I suppose I should use some autoresizing settings, could you tell me which one is supposed to align the view to top right corner of its superview?
Asked
Active
Viewed 1.8k times
9
-
1have you checked out the autoResizing property of UIView?http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instp/UIView/autoresizingMask http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/c/tdef/UIViewAutoresizing – V1ru8 Dec 14 '11 at 15:48
-
Is the autoresizingMask only property that is required for the behaviour I described? I tried different values of autoresizingMask property but to no avail... – mgamer Dec 14 '11 at 15:52
-
You have to position the view at the correct position in the first place but then the re orientation during the rotation is done automatically by the resizing mask. – V1ru8 Dec 14 '11 at 16:05
-
What position do you mean with "top right bottom". top and bottom at once what do you mean by that? – V1ru8 Dec 14 '11 at 16:06
-
My mistake, it is "top right". – mgamer Dec 14 '11 at 16:51
1 Answers
21
UIView parentView //your full screen view
UIView view //the 200x200 view
[parentView addSubview:view];
CGRect frame = view.frame;
//align on top right
CGFloat xPosition = CGRectGetWidth(parentView.frame) - CGRectGetWidth(frame);
frame.origin = CGPointMake(ceil(xPosition), 0.0);
view.frame = frame;
//autoresizing so it stays at top right (flexible left and flexible bottom margin)
view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin
That positions the view on top right and set's the autoresizing mask so it stays at that position.

Harry Wood
- 2,220
- 2
- 24
- 46

V1ru8
- 6,139
- 4
- 30
- 46
-
1Thanks, this worked great for me. Just one modification to the last line above, that should be "view.autoresizingMask = ...". – Andrew Philips Mar 19 '13 at 03:01