从 NSRange 创建 UITextRange

Create UITextRange from NSRange(从 NSRange 创建 UITextRange)

本文介绍了从 NSRange 创建 UITextRange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在文本视图中找到不同范围的像素帧.我正在使用 - (CGRect)firstRectForRange:(UITextRange *)range; 来做到这一点.但是我不知道如何实际创建 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 说必须继承 UITextRangeUITextPosition 才能采用 UITextInput 协议.我不这样做,但我还是尝试了,按照文档的示例代码并将子类传递给 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 添加到 textview,请告诉我.我曾尝试使用 UIWebView 并将 content editable 设置为 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 方法创建文本范围.此方法需要两个位置,因此您需要计算范围开始和结束的位置.这是通过 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 NSRange 创建 UITextRange

基础教程推荐