首页 > Web开发 > 详细

UI控件(UIWebView)

时间:2016-02-16 23:27:05      阅读:266      评论:0      收藏:0      [点我收藏+]

本文主要记录UIWebView三方面内容:

1、基本的加载网页链接或文件;

2、网页js调用原生,也就是Cordova混合架构的原理;

3、原生调用js程序;

  • 原生部分主要代码:
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"WebView Test";
    
    webview_ = [[UIWebView alloc]init];
    webview_.frame = self.view.bounds;
    
    webview_.delegate = self;
    
    //自动缩放页面
    webview_.scalesPageToFit = YES;
    
    //webview提供的导航方法如下:
    //    [webView_ goBack];
    //    [webview_ goForward];
    //    [webview_ reload];
    //    [webview_ stopLoading];
 
    [self.view addSubview:webview_];
}

-(void)viewDidAppear:(BOOL)animated{
    NSLog(@"viewDidAppear");
    // 加载普通URL
    // NSURL* url;
    // http请求需要在info.plist信息中增加如下配置:
    //    <key>NSAppTransportSecurity</key>
    //    <dict>
    //    <key>NSAllowsArbitraryLoads</key>
    //    <true/>
    //    </dict>
    //    url = [[NSURL alloc]initWithString:@"http://www.baidu.com/"];
    //    [webview_ loadRequest:[NSURLRequest requestWithURL:url]];
    
    [self loadHTMLFile:@"hello.html"];
    
}

//加载一个本地html
- (void)loadHTMLFile:(NSString*)filename {
    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@""];
    NSData* data = [NSData dataWithContentsOfFile:path];
    [webview_ loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8" baseURL:nil];
}

//javascript调用原生方法,也是Cordova混合架构的原理
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"shouldStartLoadWithRequest");
    NSString *url = request.URL.absoluteString;
    NSLog(@"%@", url);
    if([url hasSuffix:@"iostest"]){
        return NO;
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //执行javascript语句
    NSLog(@"webViewDidFinishLoad");
    NSString *js = @"test2(‘hello‘)";
    [webview_ stringByEvaluatingJavaScriptFromString:js];
}


@end
  • 网页部分
<html>
    <head>
        <script type="text/javascript">
            var iFrame;
            iFrame = document.createElement(iframe);
            iFrame.style.display = none;
            document.documentElement.appendChild(iFrame);
            //创建一个iFrame,并修改其src,此时IOS中的shouldStartLoadWithRequest会被回调
            
            function test1(){
                iFrame.src = "iostest";
            }
        
            function test2(input){
                alert(input);
            }
            
        </script>
    </head>
    
    <body>
        <p>This is Test Page.</p>
        <button onclick="test1()">hello</button>
    </body>
</html>

UI控件(UIWebView)

原文:http://www.cnblogs.com/Fredric-2013/p/5193959.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!