开发者

Cocoa Touch: How to add a subview that is centered horizontally in its parent view?

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

[parent开发者_StackOverflow社区View 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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜