I have a problem that \"boundingRectForGlyphRange\" always returns CGRect.zero \"0.0, 0.0, 0.0, 0.0\". \"boundingRectForGlyphRange\" is not working. For example, I am coding
Your text kit stack is faulty. You forgot to add the text container to the layout manager! Therefore there is no text to lay out, and the layout manager cannot report any glyph rect. Therefore that glyph rect is NSRectZero, which is why you can never report a tap within it.
Another problem is that you are calling characterRangeForGlyphRange
when you should be calling glyphRangeForCharacterRange
, and you don't seem to know how to use the result (in fact, you throw away the result).
Here is working code that shows just the part about using the text stack. I start with a string "Hello to you". I will show how to learn where the rect for "to" is:
let s = "Hello to you"
let ts = NSTextStorage(
attributedString: NSAttributedString(string:s))
let lm = NSLayoutManager()
ts.addLayoutManager(lm)
let tc = NSTextContainer(size: CGSizeMake(4000,400))
lm.addTextContainer(tc) // ****
tc.lineFragmentPadding = 0
let toRange = (s as NSString).rangeOfString("to")
let gr = lm.glyphRangeForCharacterRange(
toRange, actualCharacterRange: nil) // ****
let glyphRect = lm.boundingRectForGlyphRange(
gr, inTextContainer: tc)
The result is {x 30.68 y 0 w 10.008 h 13.8}
. Now we can proceed to test whether a tap is in that rect. Go Ye And Do Likewise.