很多時候你踩,iOS原生應用快速的不能滿足我們的需求鳄橘,于是需要嵌入web頁面來實現(xiàn),這時我們需要定義一個UIWebView章办,再取得想要加載的url:
#import "WebViewController.h"
@interface WebViewController ()<UIWebViewDelegate,UIScrollViewDelegate>
{
UIActivityIndicatorView *activityIndicatorView;
}
@property(nonatomic,strong) UIWebView *webView;
@property (nonatomic, strong) id url;
@end
下面是實現(xiàn)方法:
@implementation WebViewController
- (void)viewDidLoad {
[super viewDidLoad];
_url = @"https://www.baidu.com"; //獲取URL
// 初始化webview
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
// 不顯示滾動條
_webView.scrollView.showsHorizontalScrollIndicator = NO;
_webView.scrollView.delegate = self;
_webView.delegate = self;
_webView.backgroundColor = [UIColor clearColor];
[_webView setScalesPageToFit:YES];
// 初始化無敵風火輪
activityIndicatorView = [[UIActivityIndicatorView alloc]
initWithFrame : CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)] ;
[activityIndicatorView setCenter: self.view.center] ;
// 設置風火輪樣式
[activityIndicatorView setActivityIndicatorViewStyle: UIActivityIndicatorViewStyleGray] ;
[self.view addSubview:_webView];
[self.view addSubview : activityIndicatorView] ;
// 判斷URL樣式锉走,使用不同的加載方式
if ([_url isKindOfClass:[NSString class]]) {
[self loadWebPageWithString:_url];
}else{
NSURLRequest *request =[NSURLRequest requestWithURL:_url];
[_webView loadRequest:request];
}
}
- (void)loadWebPageWithString:(NSString*)urlString
{
self.url = urlString;
NSURL *url =[NSURL URLWithString:urlString];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
}
#pragma mark - UIWebViewDelegate
/* 返回NO表示不允許加載這個請求 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
return YES;
}
// 開始加載
- (void)webViewDidStartLoad:(UIWebView *)webView{
//展示風火輪
[activityIndicatorView startAnimating] ;
}
// 完成加載
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//停止風火輪
[activityIndicatorView stopAnimating];
}
// 加載失敗
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
[activityIndicatorView stopAnimating];
if([error code] == NSURLErrorCancelled){
return;
}
}
#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGPoint point = scrollView.contentOffset;
if (point.x > 0 || point.x < 0) {
//網頁滾動時控制水平位置
scrollView.contentOffset = CGPointMake(0, point.y);
}
}
activityIndicatorView and webView.png