在iPhone的uitextview中获取光标的确切位置



如何在iPhone的UITextview中获取光标的确切位置。 我知道可以使用以下命令获取光标的位置 "text_view.selectedRange.location"。 我想要光标的 X 和 Y 坐标。我该怎么做?

CGPoint origin = myTextView.frame.origin;
NSString* myHead = [myTextView.text substringToIndex:textView.selectedRange.location];
CGSize initialSize = [myHead sizeWithFont:myTextView.font constrainedToSize:myTextView.contentSize];
NSUInteger startOfLine = [myHead 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* textTailSection = [head substringFromIndex:startOfLine];
CGSize lineTotalSize = [textTailSection sizeWithFont:myTextView.font forWidth:myTextView.contentSize.width lineBreakMode:UILineBreakModeWordWrap];
CGPoint cursorPoint = origin;
cursorPoint.x += lineTotalSize.width;
cursorPoint.y += initialSize.height - lineTotalSize.height;

光标点包含点。

最新更新