How to find a pixel-positon of a cursor in UITextView?

自古美人都是妖i 提交于 2019-11-30 09:51:30

If you target to IOS7 only you could use UITextView method:

- (CGRect)caretRectForPosition:(UITextPosition *)position;

Short sample:

NSRange range; // target location in text that you should get from somewhere, e.g. textview.selectedRange
UITextView textview; // the text view

UITextPosition *start = [textview positionFromPosition:textview.beginningOfDocument offset:range.location];
CGRect caretRect = [self caretRectForPosition:start]; // caret rect in UITextView

This is probably rather inefficient, but could you take the same basic principal of the code you have posted and take the line of text the cursor is on, and loop through each individual character and do [NSString sizeWithFont:forWidth:lineBreakMode:] to calculate each character's width, and you could add all those up for your x position? Just an idea, but may help fix the issue with word wrapping.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!