我使用的内容可编辑html加载在uiwebview。当键盘被隐藏/显示时,我需要代码来设置光标位置。
当前,当我单击webview时,键盘会出现,但内容会隐藏在键盘后面。同样的情况是,当我一直按返回键时,光标/文本会出现在webview后面或者是不可见的。
首先,我需要类似于iPad Evernote应用程序中使用的功能。因为你可以看到光标永远不会在键盘后面,它总是从键盘上方开始。
发布于 2013-02-06 13:49:20
我用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中,我在键盘显示时设置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,它解决了在多行上按“返回”或包装时出现的问题。
如果您决定这样做,则在浏览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控件。
https://stackoverflow.com/questions/13867411
复制相似问题