I want to get the length of some texts in UILabel, and change the width property of UILabel dynamically.
But I have no idea about how to set the parameters in the function boundingrect. This is the documentation of Apple Developer.
func boundingRect(with size: CGSize,
options: NSStringDrawingOptions = [],
context: NSStringDrawingContext?) -> CGRect
,and I tried like this
let attr = NSMutableAttributedString(string: "test test test test , this is test text. test test test test , this is test text. test test test test , this is test text. ")
//attr.addattributes
print(attr.boundingrect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0), option: .truncatesLastVisibleLine
,context: nil)!)
But finally I got false width in print,so why and how to get the correct one.
Use
public extension NSAttributedString {
public func width(height: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect,
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil)
return ceil(boundingBox.height)
}
}
and then get let width = attr.width(height: height) where height > 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With