简体   繁体   English

将项目居中对齐到uiview的中心

[英]Center align items to the center of a uiview

Say I have a view called parent which has two subviews child1 and child2 . 假设我有一个名为parent的视图,该视图具有两个子视图child1child2 My question is how can I center align the child1 and child2 inside parent. 我的问题是我如何居中对齐child1child2在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. 我知道我可以手动设置child1child2的中心值,但是为此我需要做一些其他的计算。 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. 您可以使用自动布局将子视图的中心X和/或中心Y水平和/或垂直约束到父视图。 See this answer for some sample code that will help you build NSLayoutConstraint s appropriate to your view. 请参阅此答案以获取一些示例代码,这些示例代码将帮助您构建适合您的视图的NSLayoutConstraint

You can also use Masonry to give you a more expressive syntax. 您还可以使用Masonry为您提供更具表现力的语法。

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 一种简单的计算方法是使用它手动将子级的x和y坐标设置为父级

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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