2

我正在使用 uiwebview 中加载的内容可编辑 html。我需要代码来设置键盘隐藏/显示时的光标位置。

目前,当我点击 webview 时,键盘会出现,但内容会隐藏在键盘后面。当我继续按下返回键时,也会发生同样的情况,光标/文本位于 webview 后面或不可见。

为了抢占先机,我需要 iPad Evernote 应用程序中使用的功能。你可以看到光标永远不会在键盘后面,它总是从键盘上方开始。

4

1 回答 1

0

我为此使用了javascript。我正在使用一个类来使代码更有条理(所以你会在代码中看到一些this),但这不是必需的。

// this is used to get the current coordinates of the selection - not very efficient, so it shouldn't be called too often
this.updateOffset = function() {
  try{
    var sel = window.getSelection();
    range = sel.getRangeAt(0);
    if(this.tmpSpan==null){
      this.tmpSpan = document.createElement('span');
    }
    range.insertNode(this.tmpSpan);
    this.yOffset = this.tmpSpan.offsetTop;
    this.xOffset = this.tmpSpan.offsetLeft;
    this.tmpSpan.parentNode.removeChild(this.tmpSpan);
  }
  catch(exc){
    log('updateOffset:' + exc.toString());
  }
}

// eContent is the div with 'contenteditable', while visibleHeight is an int, set from objective-c (depending on where the webview is positioned, keyboard height and screen height)
this.scrollToVisible = function(){
  try {
    if(this.eContent.clientHeight>this.visibleHeight){
      this.updateOffset();
      if(this.yOffset<window.pageYOffset){
        window.scrollTo(0, this.yOffset);
      }
      else if(this.yOffset-window.pageYOffset>this.visibleHeight){
        window.scrollTo(0, this.yOffset-this.visibleHeight);
      }
    }
  }
  catch (exc){
    log('scrollToVisible: ', exc.toString());
  }
}

在objective-c中,我在键盘显示期间设置visibleHeight,然后在键盘显示scrollToVisible完成时调用。

-(void)setVisibleHeight:(int)height{
    [self stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"docState.visibleHeight=%d", height]];
}
-(void)scrollToVisible{
    [self stringByEvaluatingJavaScriptFromString:@"docState.scrollToVisible()"];
}

scrollToVisible在 javascript 事件上也被调用:onkeyup、onpaset、oncut,它修复了按下“return”或换行时的问题。

如果您决定采用这种方式,则在滚动浏览 javascript 时需要非常小心,否则可能会导致 UIWebview 控件出现一些问题(例如:将光标放在错误的位置,将光标自动移动到顶部文件等)

编辑
关于visibleHeight. 据我所知,我使用它是因为我无法从 javascript 中获得实际的可见高度(document.body.clientHeight还包括键盘后面的区域)。

由于我正在UIWebView全屏显示,因此我将可见高度设置如下:

- (void)keyboardWillShow:(NSNotification *)notification {
    ...
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGRect kbRect = [self.window convertRect:keyboardRect fromView:nil];
    _kbRect = kbRect;

    CGPoint sorigin = [self.superview convertPoint:self.frame.origin toView:nil];
    int visibleHeight = _kbRect.origin.y-sorigin.y-_tlbInputAccessory.frame.size.height-lkPadBottom; // _tlbInputAccessory is a custom accessory view
    [self stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"docState.setVisibleHeight(%d)", height]];
    ...
}

请注意,我是从 的子类调用它UIWebView,因此self将表示UIWebView控件。

于 2013-02-06T13:49:20.033 回答