允许标签使用不进行字符换行所需的首选宽度(启用自动换行时)

问题描述 投票:0回答:1

我有一个 UILabel,其中 3 行设置为自动换行。我还将标签的宽度设置为 180。虽然这在几乎所有情况下都有效,但某些单词很长的语言开始进行字符换行,因为它们的长度大于 180。理想情况下,我会让标签保持在所有情况下都是 180,除非单词太长而无法容纳。然后,我想将宽度扩大到最小尺寸,以保持最长的单词完好无损。关于如何做到这一点有什么建议吗?

let myString = "thisisaveryveryveryveryverylongstring"
let myLabel = UILabel()
myLabel.text = myString
mylabel.numberOfLines = 3
myLabel.lineBreakMode = .byWordWrapping
myLabel.widthAnchor.constraint(equalToConstant: 180).isActive = true

我尝试设置preferredWidth以及将宽度约束设置为优先级小于1000,但在这两种情况下,较长的单词仍然字符换行。

ios swift uilabel
1个回答
0
投票

要实现 UILabel 最多包含三行、自动缩小文本以适合这些行以及动态调整行数的所需行为,您可以按照以下步骤操作:

  •   Create your UILabel and set its properties as follows:
    

迅速

let myString = "thisisaveryveryveryveryverylongstring" let myLabel = UILabel() myLabel.text = myString myLabel.numberOfLines = 0 // 允许动态行数 myLabel.lineBreakMode = .byWordWrapping myLabel.translatesAutoresizingMaskIntoConstraints = false // 确保启用自动布局

  •   Set up the width constraint to limit the label's width to a maximum of 180:
    

迅速

let widthConstraint = myLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 180) widthConstraint.priority = .required widthConstraint.isActive = true

  •   Define the minimum font size for auto-shrinking by using the minimumScaleFactor property. Adjust this value as needed based on your design requirements:
    

迅速

myLabel.minimumScaleFactor = 0.5 // 根据需要调整 myLabel.adjustsFontSizeToFitWidth = true

  •   Add your label to the view hierarchy and make sure you have appropriate constraints to position it within its superview.
    

通过这些设置,标签将自动调整其字体大小以适应指定的宽度(180),并确保文本最多保持在三行之内。如果文本太长而无法容纳,它会缩小字体大小,同时将其保持在三行以内。将 numberOfLines 设置为 0 允许标签根据内容动态调整行数。 您可以微调minimumScaleFactor 值来控制字体大小可以缩小的程度,同时自动调整标签框架内的文本。这种方法为您的 UILabel 需求提供了灵活且响应迅速的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.