I want to determine the “amount” of text that fits into a given text container/bounding box.
However, no matter how I setup my text container, I always get all glyphs/characters returned. This is my playground test code:
import UIKit
let height = 30
let width = 50
let text = "Dame Henrietta Barnett (1851-1936) was a social reformer and philanthropist known for her significant contributions to improving the lives of the urban poor in London during the late 19th and early 20th centuries. She is best known as the founder of Hampstead Garden Suburb, a pioneering model of urban planning that aimed to create a harmonious blend of town and country living."
let size = CGSize(width: width, height: height)
let textContainer = NSTextContainer(size: size)
textContainer.lineFragmentPadding = 0
textContainer.lineBreakMode = .byClipping
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(textContainer)
let font = UIFont.systemFont(ofSize: 18)
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
]
let textStorage = NSTextStorage(string: text, attributes: attributes)
textStorage.addLayoutManager(layoutManager)
let glyphRange = layoutManager.glyphRange(for: textContainer)
let characterRange = layoutManager.glyphRange(forBoundingRect: CGRect(x: 0, y: 0, width: 1, height: 1), in: textContainer)
let visibleText = (text as NSString).substring(with: characterRange)
NSLog("Visible text: (visibleText)")
The value of “visibleText” is the full text.
If I specify a width / height of 0
the range is 0
, which makes sense.
Note: I know that with a width and height it should probably not return any range, I am confused to why it does (specifying any other range e.g. w: 100, height: 40, also returns the full text)
I also tried using
let characterRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
but this has the same problem.