简体   繁体   中英

Center align items to the center of a uiview

Say I have a view called parent which has two subviews child1 and child2 . My question is how can I center align the child1 and child2 inside parent. I know I could manually set the center values of child1 and child2 manually but for that Ill need to do some other calculations. My question is if there is a method that the does this for us and center aligns the items ?

You can use auto-layout to constraint the child views' center X and/or center Y to the parent horizontally and/or vertically. See this answer for some sample code that will help you build NSLayoutConstraint s appropriate to your view.

You can also use Masonry to give you a more expressive syntax.

An easy way to calculate it would be to use this to manually set the x and y coordinates of the child to the parent

[parent addSubView:child1];
child1.position = CGPointMake(CGRectGetMidX(parent.frame), CGRectGetMidY(parent.frame));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM