对于给定的NSRange
,我希望在UILabel
中找到与这NSRange
的字形相对应的CGRect
.例如,我想找出在句子"敏捷的棕色狐狸跳过懒狗"中包含"狗"这个词的CGRect
.
诀窍是,UILabel
有多行,而文本实际上是attributedText
,所以要找到字符串的确切位置有点困难.
我想要在我的UILabel
子类上编写的方法如下所示:
- (CGRect)rectForSubstringWithRange:(NSRange)range;
Details, for those who are interested:个
我的目标是能够达到create a new UILabel with the exact appearance and position of the UILabel, that I can then animate.我已经搞定了剩下的部分,但正是这一步阻碍了我.
What I've done to try and solve the issue so far:个
- 我曾希望在iOS7中会有一些Text Kit来解决这个问题,但是我看到的大多数Text Kit的例子都集中在
UITextView
和UITextField
上,而不是UILabel
. - 我在这里看到了另一个关于Stack Overflow的问题,它promise 解决这个问题,但公认的答案已经有两年多了,而且代码在处理属性文本时执行得不好.
I'd bet that the right answer to this involves one of the following:个
- 使用标准文本工具包方法在一行代码中解决此问题.我打赌会涉及
NSLayoutManager
和textContainerForGlyphAtIndex:effectiveRange
- 编写一个复杂的方法,将UILabel分解成行,并查找行中字形的RET,可能使用Core Text方法.我目前最好的 Select 是拆解@mattt's个优秀的TTTAttributedLabel,它有一个方法可以在某个点处找到一个字形--如果我反转一下,找到一个字形的点,可能会行得通.
更新:这里有一个github要点,其中包括我迄今为止试图解决这个问题的三件事:https://gist.github.com/bryanjclark/7036101