問題描述
我需要在文本視圖中找到不同范圍的像素幀.我正在使用 - (CGRect)firstRectForRange:(UITextRange *)range;
來做到這一點(diǎn).但是我不知道如何實(shí)際創(chuàng)建 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
.
基本上這就是我要找的東西:
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
協(xié)議.我不這樣做,但我還是嘗試了,按照文檔的示例代碼并將子類傳遞給 firstRectForRange
導(dǎo)致崩潰.
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.
如果有更簡(jiǎn)單的方法可以將不同顏色的 UILables
添加到 textview,請(qǐng)告訴我.我曾嘗試使用 UIWebView 并將 content editable
設(shè)置為 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.
提前致謝.
推薦答案
您可以使用 textRangeFromPosition:toPosition
方法創(chuàng)建文本范圍.此方法需要兩個(gè)位置,因此您需要計(jì)算范圍開始和結(jié)束的位置.這是通過 positionFromPosition:offset
方法完成的,該方法從另一個(gè)位置返回一個(gè)位置和一個(gè)字符偏移量.
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];
}
這篇關(guān)于從 NSRange 創(chuàng)建 UITextRange的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!