多行自动收缩标签 Swift
Auto shrink label with multiple lines Swift
我在不使用故事板的情况下制作应用程序。该应用程序的文本很长,所以我无法在一行中读够 space。该应用程序适用于 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
具有任意行数,其中文本包含在一定宽度内,请继续阅读:
您的操作取决于您是否使用 AutoLayout:
不是自动布局
只需使用:
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
AutoLayout
首先,您应该将 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
}
}
我在不使用故事板的情况下制作应用程序。该应用程序的文本很长,所以我无法在一行中读够 space。该应用程序适用于 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
具有任意行数,其中文本包含在一定宽度内,请继续阅读:
您的操作取决于您是否使用 AutoLayout:
不是自动布局
只需使用:
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
AutoLayout
首先,您应该将 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
}
}