Get caret rect in content-editable UIWebView when it's on a blank line

↘锁芯ラ 提交于 2020-01-06 02:48:27

问题


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:


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.



来源:https://stackoverflow.com/questions/24467062/get-caret-rect-in-content-editable-uiwebview-when-its-on-a-blank-line

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