1. 程式人生 > >iOS webView載入本地html、css、js檔案

iOS webView載入本地html、css、js檔案

1.h5本地html檔案,載入到web view上面,不需要網路亦可以加載出來。
2.h5內容格式設定檔案寫法

文章內容
在IOS開發中,可以通過webView來載入HTML檔案
步驟如下:
1.需要有一個webView,可以通過storyboard拖拽一個 或者 alloc 一個(我在這裡是拖拽了一個),是否要給webView設定delegate ,根據自己的需要決定(如果只是展示頁面可以忽略)。

2.建立HTML檔案、CSS檔案、js檔案,同樣的建立方式,只是字尾名不同。
New File -> Other ->Empty
建立HTML檔案字尾名為:html,建立css檔案字尾名為css,建立js檔案字尾名為:js

這裡寫圖片描述

3.在HTML檔案,css檔案,js檔案中寫入我們的程式碼。
在HTML檔案中寫入一些元素

<!DOCTYPE html>
<html>
<head lang="zh">

    <meta charset="UTF-8">

    <title>第一個HTML</title>

    <link rel="stylesheet" type="text/css" href="index1.css">

    <script type="text/javascript" src="index1.js"
>
</script> </head> <body> <h1>我是HTML</h1> <p id = "p">p標籤</p> <img id = "img" src = "image.png" alt = "百度LOGO"><br/> <a id = "a" href="https://www.baidu.com">我要到百度</a> <br/><br/><br/> <button
onclick = "hello()">
點選我彈出hello</button> </body> </html>

在css檔案中改變元素的屬性

#p{
    color:red;
}
#img{
    width:120px;
    height:50px;
}
#a{

    color:yellow;
}

在js檔案中寫一個彈窗的函式

function hello(){
    alert("hello");
}
//
//  ViewController.m
//  ios-loadHtml
//


#import "ViewController.h"

@interface ViewController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Load HTML";
    [self loadHTMLFile];
}

//Load
-(void)loadHTMLFile{
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index1"
                                                          ofType:@"html"];
    NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath
                                                    encoding:NSUTF8StringEncoding
                                                       error:nil];
    [self.webView loadHTMLString:htmlCont baseURL:baseURL];
}
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType{

    NSURL* url = [request URL];
    NSString* urlstring = [NSString stringWithFormat:@"%@",url];
//    if ([urlstring isEqualToString:@"http://baidu.com/"]) {
//        return NO;
//    }
    NSLog(@"url = >%@",url);

    return YES;
}





@end

專案截圖:
這裡寫圖片描述

這裡寫圖片描述