iOS中UIWebView网页加载组件的基础及使用技巧实例
基本用法示例
-(void)viewDidLoad
{
[superviewDidLoad];
//Doanyadditionalsetupafterloadingtheview.
UIWebView*webView=[[UIWebViewalloc]initWithFrame:CGRectMake(0,20,ScreenWidth,ScreenHeight-20)];
//自动队页面进行缩放以适应屏幕
webView.scalesPageToFit=YES;
webView.userInteractionEnabled=YES;
webView.opaque=YES;
[self.viewaddSubview:webView];
NSURL*url=[NSURLURLWithString:@"http://www.youku.com"];
NSURLRequest*request=[NSURLRequestrequestWithURL:url];
[webViewloadRequest:request];
//NSString*myHT=@"优酷";
//[webViewloadHTMLString:myHTbaseURL:url];
/*
[webViewgoBack];//返回
[webViewgoForward];//前往
[webViewreload];
[webViewstopLoading];
*/
webView.delegate=self;
//移除滚动后的外边阴影
UIScrollView*scrollView=webView.scrollView;
for(inti=0;i<scrollView.subviews.count;i++){
UIView*view=[scrollView.subviewsobjectAtIndex:i];
if([viewisKindOfClass:[UIImageViewclass]]){
view.hidden=YES;
}
}
}
#pragmamark-UIWebViewDelegate
-(BOOL)webView:(UIWebView*)webViewshouldStartLoadWithRequest:(NSURLRequest*)requestnavigationType:(UIWebViewNavigationType)navigationType{
/**
*typedefNS_ENUM(NSInteger,UIWebViewNavigationType){
*UIWebViewNavigationTypeLinkClicked,
*UIWebViewNavigationTypeFormSubmitted,
*UIWebViewNavigationTypeBackForward,
*UIWebViewNavigationTypeReload,
*UIWebViewNavigationTypeFormResubmitted,
*UIWebViewNavigationTypeOther
};
*/
NSLOG_FUNCTION;
returnYES;
}
//开始加载
-(void)webViewDidStartLoad:(UIWebView*)webView{
NSLOG_FUNCTION;
}
//完成加载
-(void)webViewDidFinishLoad:(UIWebView*)webView{
NSLOG_FUNCTION;
}
//加载失败,弹出错误提示
-(void)webView:(UIWebView*)webViewdidFailLoadWithError:(NSError*)error{
UIAlertView*alterview=[[UIAlertViewalloc]initWithTitle:@""message:[errorlocalizedDescription]
delegate:nilcancelButtonTitle:nilotherButtonTitles:@"OK",nil];
[alterviewshow];
[alterviewrelease];
NSLOG_FUNCTION;
}
以下是关于它的一些使用技巧:
1.让网页适应手机屏幕宽度
如果用UIWebView显示一些pc站的网页,会发现网页会超出屏幕,显得很不好看,这时可以在webViewDidFinishLoad这个代理里面通过js添加一个meta:
-(void)webViewDidFinishLoad:(UIWebView*)webView
{
NSString*meta=[NSStringstringWithFormat:@"document.getElementsByName(\"viewport\")[0].content=\"width=%f,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no\"",IPHONE_WIDTH];
[webViewstringByEvaluatingJavaScriptFromString:meta];
}
注意:使用这个方法时要把UIWebView的scalesPageToFit设成NO
webView.scalesPageToFit=NO;
2.为网页中的图片添加点击事件,当点击图片时放大查看
思路是给每一个img标签添加onclick事件,在事件中把img的src属性封装成一个特殊的url,然后进行拦截
如果是通过loadHTMLString去加载网页的话,可以执行下面一句进行替换:
html=[htmlstringByReplacingOccurrencesOfString:@"<img"withString:@"<imgonclick=\"window.location.href=('http://src.'+this.src);\""];