我正在制作一个不使用 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/