Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 in Xcode 9 - How to use boundingrect in NSAttributedstring?

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.

like image 406
Sidney Liu Avatar asked Oct 16 '25 04:10

Sidney Liu


1 Answers

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

like image 170
tereks Avatar answered Oct 17 '25 21:10

tereks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!