Kalzem
Kalzem

Reputation: 7501

How to get height of string with maximum lines using NSTextStorage?

I am trying to get the height of an attributed string (for any font, any language, any strange utf8 characters, etc).

I found this interesting topic at Badoo Chatto about different solutions: https://github.com/badoo/Chatto/issues/129

And the solution I'm using is theirs:

func height(width: CGFloat, attributes: [NSAttributedString.Key: Any]) -> CGFloat {
    let textContainer: NSTextContainer = {
        let container = NSTextContainer(size: CGSize(width: width, height: .greatestFiniteMagnitude))
        container.lineFragmentPadding = 0
        return container
    }()
    let textStorage = NSTextStorage(string: self, attributes: attributes)
    let layoutManager: NSLayoutManager = {
        let layoutManager = NSLayoutManager()
        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)
        return layoutManager
    }()

    let rect = layoutManager.usedRect(for: textContainer)
    return rect.size.round().height
}

How can I modify this logic so that it can take into consideration a maximum line number?

I tried adding container.maximumNumberOfLines = 2 but it won't change anything as NSTextContainer is set with an infinite height.

Ideally I would like to avoid using any UIView or subview as this processing has to be done in a background thread. Also, it appears that any UIKit-based solution isn't 100% reliable (cf the Badoo Chatto link).

Upvotes: 2

Views: 331

Answers (0)

Related Questions