如何将两个 UILabel 连续放置,以便它们根据 iOS 中的文本大小垂直居中?

Posted

技术标签:

【中文标题】如何将两个 UILabel 连续放置,以便它们根据 iOS 中的文本大小垂直居中?【英文标题】:How to place two UILabels in a row so that they center vertically based on the size of the text in iOS? 【发布时间】:2017-07-31 08:08:42 【问题描述】:

我有一个带有标签和按钮的表格行,它们都应该根据显示的文本垂直居中。这意味着行的高度应该基于最大的文本。见下图:

我尝试通过将换行符设置为 WordWrap 并将两者垂直居中来做到这一点,但是右侧的 UIButton 没有相应地缩放。

约束:

*label* top 5 to contentview
*label* bottom 5 to contentview
*label* leading 5 to contentview
*label* width 0.75 of contentview

*button* leading 5 to label
*button* trailing 5 to contentview
*button* bottom 5 to contentview
*button* top 5 to contentview                                  

【问题讨论】:

你在使用 UITableViewAutomaticDimension 吗? 是的,UITableViewAutomaticDimension 已设置 UIButton 不会展开,因此您可以使用 UILabel 代替 UIButton。 【参考方案1】:

试试这个设置

正确的标签

左标签

现在把按钮放在右边的标签上,像这样

【讨论】:

【参考方案2】:

不要对任何视图设置高度限制。只需为标签和按钮设置顶部和底部约束,以及明显的前导和尾随。

您甚至不需要使它们垂直居中,如果它们具有相同的顶部和底部边距,UITableViewCell 将为您完美地包裹它们。

【讨论】:

【参考方案3】:

为两个标签设置文本后,您可以获得两个标签的endY 并在tableView 委托中返回相应的height+padding

【讨论】:

以上是关于如何将两个 UILabel 连续放置,以便它们根据 iOS 中的文本大小垂直居中?的主要内容,如果未能解决你的问题,请参考以下文章

像素完美UILabel

替换 UILabel 的 minimumFontSize

如何将UILabel放置在导航栏的中心

如何将 UILabel 放置在 UIImageView 下方,使其始终均匀放置

在哪里放置应用程序以便无论工作目录如何我都可以使用它们?

如何在滚动视图中使 UIImage 低于 UILabel 或 UITextView