加載本地檔案代碼:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGRect bounds = [[UIScreen mainScreen]bounds];
UIWebView* webView = [[UIWebView alloc]initWithFrame:bounds];
webView.scalesPageToFit = YES;//自動對頁面進行縮放以适應螢幕
[self.view addSubview:webView];
NSURL *url =[NSURL URLWithString:[[NSBundle mainBundle]pathForResource:@"2-2" ofType:@"png" inDirectory:@"assets"]];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
說明:
1.拖動檔案到Xcode,提示兩個選擇,“create groups”和“create folder references”,預設情況下為第一種,即所有加入到項目的檔案都會在mainBundle根路徑下,即不管加入項目的檔案的目錄結構如何,在APP中都可以通過mainBundlePath/filename來通路到;如果采用第二種方式,則就會保留相對路徑,需要通過mainBundlePath/path/filename來通路。通過這兩種方式到項目的檔案夾顯示具有不同的顔色。 選擇“create groups”,檔案夾顔色為黃色。
加載網頁
CGRect bounds = [[UIScreen mainScreen]applicationFrame];
UIWebView* webview = [[UIWebView alloc]initWithFrame:bounds];
[_container addSubview:webview];
NSURL* url =[NSURL URLWithString:@"https://www.baidu.com"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[webview loadRequest:request];