[英]How to set the fontsize programmatically to fit numberOflines value in swift4
I have two UILabels named headingLabel and descriptionLabel whose number of lines is 3 and 5 respectively.我有两个 UILabels 分别命名为 HeadingLabel 和 descriptionLabel,它们的行数分别为 3 和 5。 Now I want the font-size of the text to change and fit into the numberOfLines where the text varies based on some networking json data received.现在我希望文本的字体大小改变并适应 numberOfLines,其中文本根据收到的一些网络 json 数据而变化。
here is my code
let headingLabel : UILabel = {
let hl = UILabel()
hl.translatesAutoresizingMaskIntoConstraints = false
hl.text = "Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor"
hl.textColor = .black
hl.lineBreakMode = NSLineBreakMode.byWordWrapping
hl.numberOfLines = 3;
hl.sizeToFit()
hl.clipsToBounds = true
hl.font = hl.font.withSize(20)
return hl
}()
let descriptionLabel : UILabel = {
let dl = UILabel()
dl.translatesAutoresizingMaskIntoConstraints = false
dl.text = "Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolorLorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor"
dl.textColor = .black
dl.lineBreakMode = NSLineBreakMode.byWordWrapping
dl.numberOfLines = 5
dl.font = dl.font.withSize(18)
dl.sizeToFit()
dl.clipsToBounds = true
dl.alpha = 0.8
return dl
}()
Use Autoshrink to adjust text into label frame.使用 Autoshrink 将文本调整为标签框架。
Determines whether the label adjusts the appearance of the text before resorting to truncation.确定标签在诉诸截断之前是否调整文本的外观。 Choose Minimum Font Scale and enter a value to allow the label to reduce the font size to fit the text.选择最小字体比例并输入一个值以允许标签减小字体大小以适应文本。 Enable Tighten Letter Spacing to allow the label to reduce intercharacter spacing.启用 Tighten Letter Spacing 以允许标签减少字符间距。 Access these values at runtime with the minimumScaleFactor and allowsDefaultTighteningForTruncation properties, respectively.在运行时分别使用 minimumScaleFactor 和 allowedDefaultTighteningForTruncation 属性访问这些值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.