UITextView获取选中的文本点

发布于 2024-12-23 09:23:53 字数 54 浏览 2 评论 0原文

我想知道有什么方法可以获取 UITextView 中所选文本的要点吗?

谢谢!

I was wondering is there any way to get the point of the selected text in UITextView ?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酸甜透明夹心 2024-12-30 09:23:53

对于 iOS5 及更高版本:现在 UITextFieldUITextView 符合 UITextInput 协议,因此可以:)

选择插入符号之前的最后 5 个字符像这样:

//Get current selected range , this example assumes is an insertion point or empty selection
UITextRange *selectedRange = [textField selectedTextRange];

NSLog("Start: %d <> End: %d", selectedRange.start, selectedRange.end);

//Calculate the new position, - for left and + for right
UITextPosition *newPosition = [textField positionFromPosition:selectedRange.start offset:-5];

//Construct a new range using the object that adopts the UITextInput, our textfield
UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:selectedRange.start];

For iOS5 and above : Now UITextField and UITextView conform to UITextInput protocol so it is possible :)

Selecting the last 5 characters before the caret would be like this:

//Get current selected range , this example assumes is an insertion point or empty selection
UITextRange *selectedRange = [textField selectedTextRange];

NSLog("Start: %d <> End: %d", selectedRange.start, selectedRange.end);

//Calculate the new position, - for left and + for right
UITextPosition *newPosition = [textField positionFromPosition:selectedRange.start offset:-5];

//Construct a new range using the object that adopts the UITextInput, our textfield
UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:selectedRange.start];
静待花开 2024-12-30 09:23:53

是的,首先像这样获取活动选择:myTextView.selectedRange,然后将其传递给此方法[myTextView firstRectForRange:range]这将为您提供第一个边界矩形(其中如果是一行,则为整个选区;如果是多行,则为第一行上的选区区域)作为 CGRect

Yes, first get the active selection like this: myTextView.selectedRange and then pass it to this method [myTextView firstRectForRange:range] This will give you the first bounding rectangle (which is the entire selection if it is one line, and the area of the selection on the first line if it is multi-line) as a CGRect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文