如何将任何子视图水平居中在父UIView中,但不垂直居中?

11

如何将任何子视图水平居中在其父UIview中,而不是垂直居中。我尝试了 child.center = parent.center 但它会将我的子视图水平和垂直都放在父视图的中心。如何将其仅水平对齐在中心位置。谢谢。


1
仅设置 center.x 值,忽略 y 值。 - Jageen
中心点是一个CGPoint。你只需要将其x值设置为父视图的中心x值即可。 - Steve
4个回答

31

像这样仅更改中心可能会有所帮助

child.center = CGPointMake(CGRectGetMidX(parentView.bounds), child.center.y);

请问一下,child.center.y 和 child.origin.y 有区别吗? - Zeebok
1
@ChrisH 是的,我在答案中犯了一个错误。感谢你指出来。 - Jaideep Nagra
@Zeebok中心点表示它在其父视图坐标系中的中心位置,而原点表示视图在其父视图坐标系中的位置。有关详细说明,请查看此stackoverflow问题。 - Jaideep Nagra
1
@Jaideep np - 你还可以更进一步,使用parent.center.x作为第一个值。 - ChrisH

2

您不能直接修改UIViewControllercenter属性中的x值,但可以采取以下措施:

CGPoint center = child.center;
center.x = parent.center.x;
child.center = center;

非常感谢Jaideep,你的回答太棒了。你的回答很容易理解,但我有点困惑。Jaideep也给出了一个很好的答案,我不知道该接受哪一个。你们两个都很棒。 - Zeebok

1
尝试一下,
subview.frame = CGRectMake(((parentView.frame.size.width/2)-(subview.frame.size.width/2)),subview.frame.origin.y,subview.frame.size.width,subview.frame.size.height);

0

我需要在每个不同的设备尺寸上水平居中(但不是垂直)一个UIImageView,所以我使用了这个方法,效果很好:

CGRect screenRect = [[UIScreen mainScreen] bounds];
[self.myImageView setCenter:CGPointMake(CGRectGetMidX(screenRect), self.myImageView.frame.origin.y + self.myImageView.frame.size.height/2)];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接