ios 如何在 XCode 6 中对齐标签垂直中心

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25128788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:42:33  来源:igfitidea点击:

How do I align a label vertical center in XCode 6

iosswiftxcode6

提问by botbot

Whenever I add constraints to the height and width of my UILabel, the text will then jump to the top of the controller.

每当我对 UILabel 的高度和宽度添加约束时,文本就会跳到控制器的顶部。

How can I verticallycenter the UILabel in the ViewController? Image of contstraints

如何在 ViewController 中垂直居中 UILabel? 约束的图像

enter image description here

在此处输入图片说明

回答by mohacs

click on Align button on bottom toolbar in IB then select Horizontal or Vertical center. First you might want to fix width and height as well, if you want to preserve size.

单击 IB 底部工具栏上的对齐按钮,然后选择水平或垂直居中。首先,如果您想保留大小,您可能还想固定宽度和高度。

enter image description here

在此处输入图片说明

回答by Justin Moser

For an explanation of why this happens:

关于为什么会发生这种情况的解释:

Whenever you add constraints to a view in interface builder you are telling IB that you want to opt in to auto layout and now you have to take full control of the layout. The reason you see the label at the top of the superview is because you haven't added any constraints that determine the label's location within the superview. See mohacs answer on how to add the constraints.

每当您在界面构建器中向视图添加约束时,您都在告诉 IB 您想要选择自动布局,现在您必须完全控制布局。您在父视图顶部看到标签的原因是您没有添加任何约束来确定标签在父视图中的位置。有关如何添加约束,请参阅 mohacs 答案。

回答by nikhil nangia

In case someone still need that here's how you can do programatically

如果有人仍然需要,这是您可以通过编程方式进行的操作

let centerCoordinate = self.view.frame.maxY - (self.view.frame.maxY/2.0)
label.frame = CGRectMake(centerCoordinate,
100, 50, 50)