iOS中UIWebView的科学使用方法总结

众所周知,没有哪一个工具能像html/css那样如此轻易的构建复杂的界面,为了保证良好的用户体验,有时我们可能会选择使用html的方式来展示复杂度高,复用性低的界面,在iOS平台,选择UIWebView是非常自然的,那么我根据最近的一个iPad上的珠宝导购项目来向大家总结一下iOS平台结合HTML5使用UIWebView的小Tips。

1、加载本地html代码

这段代码加载了项目资源路径下www目录里面的index.html文件

	NSString *path = [[NSBundle mainBundle]pathForResource:@"index" ofType:@"html" inDirectory:@"www"];
        NSURL *url = [NSURL fileURLWithPath:path];
        NSURLRequest *req = [NSURLRequest requestWithURL:url];
        [_webView loadRequest:req];


2、加载网络html代码

        NSString *fullURL = @"http://ruby-china.org/";
        NSURL *url = [NSURL URLWithString:fullURL];
        NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
        [_webView loadRequest:requestObj];

3、原生代码运行页面里面的js代码

[self.webView stringByEvaluatingJavaScriptFromString:@"alert("Calling from native code");"];

4、响应式布局

对于针对html5平台的html页面,一般都会在head里面添加这样的代码,它能自适应不同尺寸和分辨率密度的屏幕

5、针对触摸屏优化

这是一段非常神奇的js代码,能够让你的页面中所有标签的跳转,在触摸屏上面的响应速度有一个质的飞跃!对于用户体验的提升,能使得html页面最大化的近似原生应用。


{
    var touching_flag = false;

    $(document).on('touchstart', "a:not(.notouch):not([href='#'])", function () {
        if (!touching_flag) {
            touching_flag = true;
        }
        window.setTimeout(function () {
            touching_flag = false;
        }, 0);
        return false;
    });

    $(document).on('touchend', "a:not(.notouch):not([href='#'])", function () {
    	window.location.href = $(this).attr('href');
        touching_flag = false;
    });

}


6、通过js调用原生代码

首先,在初始化webview的时候,在你的ViewController里面令

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.webView.delegate = self;
}

把webview的delegate指向当前类(类似Java里面的接口实现),然后在ViewController里面实现这个方法

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    NSString *jsMethodString = [[request URL] absoluteString];
    NSLog(@"jsMethodString ===> %@", jsMethodString);
}

接下来,你就能在html里面通过调用js来触发上面那个方法了:


function myAlert(msg) {
    alert(msg);
    window.location = 'ios:' + msg;
}


 如果你在js里面调用myAlert("This is a message from js!");接下来你应该可以在Xcode的console里面看见这样的console输出:


jsMethodString ===> ios:This is a message from js!


7、对于提升用户体验非常有用的十个代码片段

http://www.jquery4u.com/plugins/10-jquery-ipad-code-snippets-plugins/


你可能感兴趣的:(iOS中UIWebView的科学使用方法总结)