从NSRange创建UITextRange [英] Create UITextRange from NSRange
问题描述
我需要在textview中找到不同范围的像素框架。我正在使用 - (CGRect)firstRectForRange:(UITextRange *)范围;
来执行此操作。但是我无法找到如何实际创建 UITextRange
。
I need to find the pixel-frame for different ranges in a textview. I'm using the - (CGRect)firstRectForRange:(UITextRange *)range;
to do it. However I can't find out how to actually create a UITextRange
.
基本上这就是我在寻找的东西for:
Basically this is what I'm looking for:
- (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView {
UITextRange*range2 = [UITextRange rangeWithNSRange:range]; //DOES NOT EXIST
CGRect rect = [textView firstRectForRange:range2];
return rect;
}
Apple说必须子类 UITextRange
和 UITextPosition
以采用 UITextInput
协议。我不这样做,但我还是尝试了,按照doc的示例代码并将子类传递给 firstRectForRange
,这导致崩溃。
Apple says one has to subclass UITextRange
and UITextPosition
in order to adopt the UITextInput
protocol. I don't do that, but I tried anyway, following the doc's example code and passing the subclass to firstRectForRange
which resulted in crashing.
如果有更简单的方法可以在文本视图中添加不同颜色的 UILables
,请告诉我。我尝试使用UIWebView,内容可编辑
设置为TRUE,但我不喜欢与JS通信,并且着色是我唯一需要的东西。
If there is a easier way of adding different colored UILables
to a textview, please tell me. I have tried using UIWebView with content editable
set to TRUE, but I'm not fond of communicating with JS, and coloring is the only thing I need.
提前致谢。
推荐答案
您可以使用方法<$创建文本范围C $ C> textRangeFromPosition:toPosition 。此方法需要两个位置,因此您需要计算范围开始和结束的位置。这是通过方法 positionFromPosition:offset
完成的,它从另一个位置和一个字符偏移量返回一个位置。
You can create a text range with the method textRangeFromPosition:toPosition
. This method requires two positions, so you need to compute the positions for the start and the end of your range. That is done with the method positionFromPosition:offset
, which returns a position from another position and a character offset.
- (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView
{
UITextPosition *beginning = textView.beginningOfDocument;
UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
UITextPosition *end = [textView positionFromPosition:start offset:range.length];
UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];
CGRect rect = [textView firstRectForRange:textRange];
return [textView convertRect:rect fromView:textView.textInputView];
}
这篇关于从NSRange创建UITextRange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!