iOS - 将两个标签放在其超级视图的中心

iOS - Placing two label together in centre of their super view(iOS - 将两个标签放在其超级视图的中心)

本文介绍了iOS - 将两个标签放在其超级视图的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个标签,L1 和 L2,长度可变且不相同.我想在 Xcode 中使用约束放置这两个标签.如果可能的话,我不想以编程方式操纵约束.将不胜感激.

I have two label, L1 and L2 of variable and nonidentical length. I want to place these two label using constraints in Xcode. If possible i don't want to manipulate constraints programmatically. guidance will be appreciated.

正确的图像应该是预期的输出

Right image should be the expected output

要求,

  1. 两个标签的宽度不相同
  2. 当运行 L1 的前导空格和 L2 的尾随空格时将相等
  3. L1 和 L1 之间的距离L2,水平间距固定,10 px
  4. UIStackView 无法使用

我怎样才能从 Xcode 中做到这一点?

How can I do it from Xcode?

推荐答案

你可以做的是将 UILabel 放在 UIView 中,然后:

What you can do is put both the UILabel inside a UIView and then:

  • HEL UILabelsuperView 中添加前导、顶部和底部.
  • superView 的尾随、顶部和底部添加到您的 HEAVENLY UILabel.
  • 在两个 UILabel
  • 之间添加 10 磅的水平间距
  • Add a leading, top and bottom to the superView to your HEL UILabel.
  • Add a trailing, top and bottom to the superView to your HEAVENLY UILabel.
  • Add a horizontal spacing of 10 points between your two UILabel

现在您的 UIView 水平和垂直居中在屏幕中间.将水平居中约束优先级设置为 250.使用 >= 5 约束将 UIView 的前导和尾随空格添加到其 superView

Now center your UIView horizontally and vertically in the middle of the screen. Set the horizontally in center constraint priority to 250. Add a leading and trailing space of your UIView to its superView with a >= 5 constraint

此外,如果文本太大,则上述约束不足以完美运行(您必须将 numberOfLines 设置为 0 并且 wrap modewordWrap 以显示完整的文本并转到下一行,当然)!因为 UILabelinferred heightinferred width 的优先级为 750,每个 UILabel 的内容抗压缩优先级 默认也是 750,Xcode 会很困惑该怎么做,这是理所当然的!您可以做的是将 attributes inspector 中的 content compression 属性设置为 1000

Additionally if the text is too large then the above constraints aren't simply enough to work perfectly (You will have to set the numberOfLines to 0 and wrap mode to wordWrap to display the complete text and go to the next line, of course)! As the UILabels will have their inferred height and inferred width with a priority of 750 and the content compression resistance priority of each UILabel is 750 by default too, Xcode will be confused what to do and rightfully so! What you can do is set the content compression property in attributes inspector to 1000

如果您不想修改 抗压性(我以前觉得它们很吓人),您还可以添加一个 >= 约束到每个 UILabel 的宽度和高度.给出这个约束也可以显示完整的文本,无论它有多大,因为明确定义高度和宽度已经给了它们 1000 的优先级!

If you don't wish to tinker with compression resistance (I used to find them scary), what you can also do is add a >= constraint to the width and height both of each UILabel. Giving this constraint will also work to show the complete text no matter how large it be, as explicitly defining height and width has given them a priority of 1000!

这篇关于iOS - 将两个标签放在其超级视图的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:iOS - 将两个标签放在其超级视图的中心

基础教程推荐