let textLable = UILabel(frame: view.bounds)
textLable.text = "abcd"
textLable.font = .systemFont(ofSize: 500)
textLable.textAlignment = .center
textLable.numberOfLines = 0
view.addSubview(textLable)
动态设置字体大小
textLable.adjustsFontSizeToFitWidth = true
textLable.minimumScaleFactor = 0.02
获取字体大小
func adjustedFontSize(label: UILabel) -> CGFloat {
let text: NSMutableAttributedString = NSMutableAttributedString(attributedString: label.attributedText!)
text.setAttributes([NSAttributedString.Key.font: label.font as Any], range: NSMakeRange(0, text.length))
let context: NSStringDrawingContext = NSStringDrawingContext()
context.minimumScaleFactor = label.minimumScaleFactor
text.boundingRect(with: label.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: context)
let adjustedFontSize: CGFloat = label.font.pointSize * context.actualScaleFactor
return adjustedFontSize
}
网友评论