如何从UITextView获取所选的文本框架 [英] How can I get the selected text frame from a UITextView

查看:148
本文介绍了如何从UITextView获取所选的文本框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 UITextView 中显示一个 UIPopoverController 我得到所选文本 CGRect



谢谢!

[UITextInput selectedTextRange] 和 [UITextInput caretRectForPosition:] 解决方案

是你要找的。



[UITextInput selectedTextRange] 返回字符中的选定范围



[UITextInput caretRectForPosition:] 返回此输入中字符范围的 CGRect



UITextView 符合 UITextInput (自iOS 5开始),因此您可以为 UITextView 实例使用这些方法。



  UITextRange * selectionRange = [textView selectedTextRange]; 
CGRect selectionStartRect = [textView caretRectForPosition:selectionRange.start];
CGRect selectionEndRect = [textView caretRectForPosition:selectionRange.end];
CGPoint selectionCenterPoint =(CGPoint){(selectionStartRect.origin.x + selectionEndRect.origin.x)/ 2,(selectionStartRect.origin.y + selectionStartRect.size.height / 2)};

编辑:因为示例代码变得有点难以得到,所以我添加了一个补充图片。 / p>


I'm trying to display an UIPopoverController from the rect of a selected text in an UITextView, How can I get the selected text CGRect ?

Thanks!

解决方案

I think [UITextInput selectedTextRange] and [UITextInput caretRectForPosition:] is what you are looking for.

[UITextInput selectedTextRange] returns the selected range in character

[UITextInput caretRectForPosition:] returns the CGRect of the character range in this input.

UITextView conforms to UITextInput (since iOS 5), so you can use these methods for your UITextView instance.

It is going to be something like this.

UITextRange * selectionRange = [textView selectedTextRange];
CGRect selectionStartRect = [textView caretRectForPosition:selectionRange.start];
CGRect selectionEndRect = [textView caretRectForPosition:selectionRange.end];
CGPoint selectionCenterPoint = (CGPoint){(selectionStartRect.origin.x + selectionEndRect.origin.x)/2,(selectionStartRect.origin.y + selectionStartRect.size.height / 2)};

EDIT : Since the sample code became a little hard to get, I added an image for complementing.

这篇关于如何从UITextView获取所选的文本框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆