UITextView中光标的像素位置 [英] Pixel-Position of Cursor in UITextView

查看:132
本文介绍了UITextView中光标的像素位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在UITextView中获取光标(闪烁条)的位置(CGPoint)(相对于其内容更可取)。我不是说NSRange的位置。我需要一些东西:

Is there a way of getting the position (CGPoint) of the cursor (blinking bar) in an UITextView (preferable relative to its content). I don’t mean the location as an NSRange. I need something around:

- (CGPoint)cursorPosition;

它应该是一种非私有的API方式。

It should be a non-private API way.

推荐答案

这是痛苦的,但你可以使用 UIStringDrawing 补充的NSString 做到这一点。这是我使用的一般算法:

It's painful, but you can use the UIStringDrawing additions to NSString to do it. Here's the general algorithm I used:

CGPoint origin = textView.frame.origin;
NSString* head = [textView.text substringToIndex:textView.selectedRange.location];
CGSize initialSize = [head sizeWithFont:textView.font constrainedToSize:textView.contentSize];
NSUInteger startOfLine = [head length];
while (startOfLine > 0) {
    /*
     * 1. Adjust startOfLine to the beginning of the first word before startOfLine
     * 2. Check if drawing the substring of head up to startOfLine causes a reduction in height compared to initialSize.
     * 3. If so, then you've identified the start of the line containing the cursor, otherwise keep going.
     */
}
NSString* tail = [head substringFromIndex:startOfLine];
CGSize lineSize = [tail sizeWithFont:textView.font forWidth:textView.contentSize.width lineBreakMode:UILineBreakModeWordWrap];
CGPoint cursor = origin;
cursor.x += lineSize.width;
cursor.y += initialSize.height - lineSize.height;
return cursor;
}



我用 [NSCharacterSet whitespaceAndNewlineCharacterSet] 找到单词边界。

这也可以使用 CTFrameSetter 在<中完成(可能更有效) code> CoreText ,但这在iPhone OS 3.1.3中不可用,所以如果你的目标是iPhone,你需要坚持 UIStringDrawing

This can also be done (presumably more efficiently) using CTFrameSetter in CoreText, but that is not available in iPhone OS 3.1.3, so if you're targeting the iPhone you will need to stick to UIStringDrawing.

这篇关于UITextView中光标的像素位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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