Core Text - select text in iPhone?

↘锁芯ラ 提交于 2019-11-27 10:12:10

问题


I need to render rich text using Core Text in my view (simple formatting, multiple fonts in one line of texts, etc.). I am wondering if text rendered this way can be selected by user using (standard copy / paste function)?


回答1:


I implemented a text selection in CoreText. It is really a hard work... But it's doable.

Basically you have to save all CTLine rects and origins using CTFrameGetLineOrigins(1), CTLineGetTypographicBounds(2), CTLineGetStringRange(3) and CTLineGetOffsetForStringIndex(4).

The line rect can be calculated using the origin(1), ascent(2), descent(2) and offset(3)(4) as shown bellow.

lineRect = CGRectMake(origin.x + offset, 
                      origin.y - descent, 
                      offset, 
                      ascent + descent);

After doing that, you can test which line has the touched point looping the lines (always remember that CoreText uses inverse Y coordinates).

Knowing the line that has the touched point, you can know the letter that is located at that point (or the nearest letter) using CTLineGetStringIndexForPosition.

Here's one screenshot.

For that loupe, I used the code shown in this post.

Edit: To draw the blue background selection, you have to paint the rect using CGContextFillRect. Unfortunately, there's no background color in NSAttributedString.



来源:https://stackoverflow.com/questions/7979592/core-text-select-text-in-iphone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!