views:

37

answers:

1

Hi, my subview (childView) has a smaller width than the parent view.

[parentView addSubview:childView];

I'm wondering how I might be able to add this child centered horizontally (vertically I want it to remain the same) in the parent view. I'd like to do this in code. Right now it's adding but to the top left corner of the parent. any ideas?

Thanks!

+3  A: 
MyView *v = [[MyView alloc] init];
CGFloat parentWidth = parentview.bounds.size.width;
CGRect frame = CGRectMake(floor((parentWidth - v.width)/2),
                          0,
                          v.width,
                          v.height);
v.frame = frame;
[parentview addSubview:v];

Obviously, you will need replace v.height and width with the actual width and change the names of the variables to match your own. The key here is flooring the width of the parent minus the view, divided by 2

coneybeare
works like a charm, thank you!! however-- v.width, v.height should be v.frame.size.width, v.frame.size.height.
Shnitzel