How to get height for NSAttributedString at a fixed width

后端 未结 12 1122
萌比男神i
萌比男神i 2020-12-12 18:53

I want to do some drawing of NSAttributedStrings in fixed-width boxes, but am having trouble calculating the right height they\'ll take up when drawn. So far, I\'ve tried:

12条回答
  •  盖世英雄少女心
    2020-12-12 19:34

    I have a complex attributed string with multiple fonts and got incorrect results with a few of the above answers that I tried first. Using a UITextView gave me the correct height, but was too slow for my use case (sizing collection cells). I wrote swift code using the same general approach described in the Apple doc referenced previously and described by Erik. This gave me correct results with must faster execution than having a UITextView do the calculation.

    private func heightForString(_ str : NSAttributedString, width : CGFloat) -> CGFloat {
        let ts = NSTextStorage(attributedString: str)
    
        let size = CGSize(width:width, height:CGFloat.greatestFiniteMagnitude)
    
        let tc = NSTextContainer(size: size)
        tc.lineFragmentPadding = 0.0
    
        let lm = NSLayoutManager()
        lm.addTextContainer(tc)
    
        ts.addLayoutManager(lm)
        lm.glyphRange(forBoundingRect: CGRect(origin: .zero, size: size), in: tc)
    
        let rect = lm.usedRect(for: tc)
    
        return rect.integral.size.height
    }
    

提交回复
热议问题