ios - 多行自动收缩标签 Swift

标签 ios swift uilabel

我正在制作一个不使用 Storyboard的应用程序。该应用程序的文本很长,因此我无法在一行中获得足够的空间。该应用程序适用于 iPad 和 iPhone。 adjustSizeToFit = true 不起作用,有没有办法调整多行标签的大小?

最佳答案

UILabel 上没有名为 adjustSizeToFit 的属性。您确定您指的不是 adjustsFontSizeToFitWidth 吗?如果你查看文档,会发现:

Normally, the label text is drawn with the font you specify in the font property. If this property is set to true, however, and the text in the text property exceeds the label’s bounding rectangle, the receiver starts reducing the font size until the string fits or the minimum font size is reached. In iOS 6 and earlier, this property is effective only when the numberOfLines property is set to 1.

我不确定这是否是您想要的。

如果您想要一个具有任意行数的 UILabel,其中文本包含在一定宽度内,请继续阅读:

您的操作取决于您是否使用自动布局:

不是自动布局

只需使用:

let size = label.sizeThatFits(CGSize(width: myWidth, height: CGFloat.max))
// CGFloat.max, because we don't want to limit the UILabel's height.
label.frame.size = size

自动布局

首先,您应该将 numberOfLines 设置为零。 其次,您需要告诉 AutoLayout 每行可以有多长,这默认为标签的宽度。为此,您需要一个 UILabel 子类:

class myLabel : UILabel {
    override func layoutSubviews() {
        // 1. Get the label to set its frame correctly:
        super.layoutSubviews()

        // 2. Now the frame is set we can get the correct width 
        // and set it to the preferredMaxLayoutWidth.
        self.preferredMaxLayoutWidth = self.frame.width
    }
}

关于ios - 多行自动收缩标签 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29442865/

相关文章:

iphone - 多选分段控件

iOS Swift 删除粘贴选项

ios - "clang quit unexpectedly"(xcode 崩溃)

swift - 对于支持多个场景的应用程序,如何使用 SwiftUI 隐藏 .phonePad 类型的键盘?

ios - 如何在 UILabel 中将某些文本格式化为粗体?

ios - 在 UITableViewCell 中自动布局两个标签?

iphone - 如何将 Layar 操作连接到我的自定义 ViewController?

ios - 使用 Core Location 的 Swift 后台获取位置更新

ios - LazyVStack 在更改 SwiftUI 时初始化所有 View

ios - 如何区分元数据中的艺术家姓名/轨道名称?