Get caret rect in content-editable UIWebView when

2019-07-23 08:59发布

For some reason, I need to get the caret vertical position in a content editable UIWebView. As many methods to do that stop caret blinking (for example when creating/removing a hidden node), I use this javascript/Objective-C code:

- (CGRect)caretRect {

    NSString *js = @"function f(){ var sel = document.getSelection(); var range = sel.getRangeAt(0).cloneRange(); range.collapse(true); var r =range.getClientRects()[0]; return '{{'+r.left+','+r.top+'},{'+r.width+','+r.height+'}}'; } f();";
    NSString *result = [self.webTexteView stringByEvaluatingJavaScriptFromString:[NSString stringWithString:js]];
    CGRect rect = CGRectFromString(result);
    return rect;

}

Unfortunately, when the caret is on a blank line, this code returns a {0, 0} {0, 0} rect...

Does anybody knows how getting caret rect (at list the vertical position in pixels) in any circumstances, while keeping it blinking? Thanks!

1条回答
一夜七次
2楼-- · 2019-07-23 09:48

This answer fixed this problem for me: https://stackoverflow.com/a/6847328/135712

Basically, you need to insert a new DOM element, get its position, then remove it.

查看更多
登录 后发表回答