Why does `boundingRectForGlyphRange` return incorrect values? Am I using it incorrectly?

Say I have a UITextView, where some of the text is sized at 15pt, and some at 10pt. I want to find the rect for the actual glyphs of the small words, a rect that would perfectly wrap them. That's where I thought `boundingRectForGlyphRange` on the text view's NSLayoutManager would come in, but it doesn't seem to report accurate values in my testing.


Say I have the following code to set up the text view:


let tv = UITextView(frame: CGRect(x: 0.0, y: 50.0, width: view.bounds.width, height: view.bounds.height))

let atr = NSMutableAttributedString(string: "Lorem ipsum dolor sit amet test string that goes on and on and then continues some more for testing purposes.", attributes: [NSFontAttributeName: UIFont.systemFontOfSize(15.0)])
atr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(10.0), range: NSRange(location: 10, length: 20))
tv.attributedText = atr

tv.backgroundColor = UIColor.lightGrayColor()

view.addSubview(tv)


I then loop through every index and print out the bounding rects:


for i in 0 ... 136 {
    print(tv.layoutManager.boundingRectForGlyphRange(NSRange(location: i, length: 1), inTextContainer: tv.textContainer))
}


But for all of the first row, the bounding rect always has the same y value: 0. I know this isn't the case because some letters are smaller, and thus would be drawn further down, but it's just telling me it's the same as the larger letters (always y: 0).

What am I doing wrong here? A wrong method all together? Something sillier?

Replies

Yes. still bug. when i input thail font.



Have other way, you can use.


locationForGlyphAtIndex


use the first glyph find the X.

use the last glyph find the lastPostion.


boundingRect.origin.x += firstPosition;

boundingRect.size.width = lastPosition - firstPosition;


If you have breakLine, you need check the Text line fragement.