Create UITextRange from NSRange(从 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 说必须继承 UITextRange
和 UITextPosition
才能采用 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
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01