objective-c将关键事件发送到webview

时间:2013-09-11 01:53:23

标签: ios objective-c uiwebview key-events

只是想知道是否有办法将keyevents或文本发送到webview。

我有一个应用程序,用户可以单击按钮执行特定任务。取消按钮,用户点击了webview中的文本框需要填充。

我可以处理按钮点击事件,只是想知道我是否可以将该文本传递给webview。

我在谷歌搜索但尚未找到任何解决方案。也许我错过了什么。

无论如何,提前谢谢。

2 个答案:

答案 0 :(得分:3)

HTML方

假设以下是在您的Objective-C方法中调用它时触发的javascript方法..原生方。

<script type="text/javascript">

 var htmlTouch = 0;

//following is the function that you've assigned for a HTML button.

function button1_click()
{
htmlTouch =1; //The reason why i am setting the htmlTpuch=1,is just to identify whether it's native touch or HTML touch.
}

//javascrip function which we are going to call from oObjective-c
function toCallFromiOS() 
{

if( htmlTouch  == 1 ) 
{ 
alert("its a html touch,so pass any values to native code here.");
return 'urText';
}    

}  

//To reset the touch for next use.
function resetTheHTMLtouch() 
{
htmlTouch = 0;
}    

</script>

原生方

创建UIWebview以加载上面的html(好吧,我现在在本地做)。

self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                pathForResource:@"test" ofType:@"html"] isDirectory:NO]]];

现在将手势委托添加到整个网络视图中。

UITapGestureRecognizer *tapGestureDown = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture)];
tapGestureDown.numberOfTapsRequired = 1;
tapGestureDown.delegate = self;
[self.webView addGestureRecognizer:tapGestureDown];

// handleTapGesture是一种本机方法,在“检测它是否是原生触摸,你想要执行什么?”

-(void)handleTapGesture
{
NSLog(@"Touch is native");
}

现在我们都已经设置好了。接下来就是实现名为的委托

-shouldRecognizeSimultaneouslyWithGestureRecognizer:==>which returns BOOL value.

在webview上检测到触摸事件时,将调用已实现的委托函数。

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}

如果你添加上面的代码,那么在点击webview时,上面的委托被调用N次(有时是8,9,13等)。只有解决方案是我们应该能够知道状态触摸(无论是结束还是开始),为下次通话重置触摸事件。

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
    {
    NSString *javastr=[self.webView stringByEvaluatingJavaScriptFromString:@"toCallFromiOS();"];
    NSLog(@"This is return string from javascript==>%@",javastr);

     if((otherGestureRecognizer.state==UIGestureRecognizerStateEnded && [javastr hasPrefix:@"urText"]))
    {

    javastr= [self.webView stringByEvaluatingJavaScriptFromString:@"resetTheHTMLtouch();"];

    return NO;
    }

    return YES;

    }

如果javastr返回任何值(文本),它是HTML触摸,或者是原生触摸,则会调用“handleTapGesture”。

有关详细信息,请查看我的博客==&gt; Feel the difference between HTML touch and Native touch on UIWebView

希望这有助于你。快乐的编码...

答案 1 :(得分:0)

所以我完全忘记了iOS我可以简单地使用javascript。以防万一其他人有同样的问题。我在这里找到了解决方案

http://iphoneincubator.com/blog/windows-views/how-to-inject-javascript-functions-into-a-uiwebview

这允许您将文本输入到webview的文本框和其他位置。

谢谢大家。