很多时候,iOS原生应用快速的不能满足我们的需求,于是需要嵌入web页面来实现,这时我们需要定义一个UIWebView,再取得想要加载的url:
#import "WebViewController.h"
@interface WebViewController ()<UIWebViewDelegate,UIScrollViewDelegate>
{
UIActivityIndicatorView *activityIndicatorView;
}
@property(nonatomic,strong) UIWebView *webView;
@property (nonatomic, strong) id url;
@end
下面是实现方法:
@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);
}
}