Nếu bạn đang đấu tranh để có được chiều rộng văn bản với hỗ trợ nhiều dòng , vì vậy bạn có thể sử dụng mã tiếp theo ( Swift 5 ):
func width(text: String, height: CGFloat) -> CGFloat {
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 17)
]
let attributedText = NSAttributedString(string: text, attributes: attributes)
let constraintBox = CGSize(width: .greatestFiniteMagnitude, height: height)
let textWidth = attributedText.boundingRect(with: constraintBox, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).width.rounded(.up)
return textWidth
}
Và theo cách tương tự, bạn có thể tìm chiều cao văn bản nếu cần (chỉ cần chuyển đổi việc triển khai constraintBox):
let constraintBox = CGSize(width: maxWidth, height: .greatestFiniteMagnitude)
Hoặc đây là một chức năng thống nhất để có được kích thước văn bản với hỗ trợ đa dòng:
func labelSize(for text: String, maxWidth: CGFloat, maxHeight: CGFloat) -> CGSize {
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 17)
]
let attributedText = NSAttributedString(string: text, attributes: attributes)
let constraintBox = CGSize(width: maxWidth, height: maxHeight)
let rect = attributedText.boundingRect(with: constraintBox, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).integral
return rect.size
}
Sử dụng:
let textSize = labelSize(for: "SomeText", maxWidth: contentView.bounds.width, maxHeight: .greatestFiniteMagnitude)
let textHeight = textSize.height.rounded(.up)
let textWidth = textSize.width.rounded(.up)