Swift : tap on a part of text of UILabel

前端 未结 7 989
北海茫月
北海茫月 2020-12-02 21:36

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

7条回答
  •  春和景丽
    2020-12-02 22:16

    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.

提交回复
热议问题