您的位置:首页 > 移动开发

UIWebView设置图片的宽度适应屏幕的大小

2016-01-08 14:16 375 查看
#import "ViewController.h"

@interface ViewController ()<UIWebViewDelegate>

@property (weak, nonatomic) IBOutletUIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)uiConfig
{
self.webView.delegate =self;
}

#pragma mark - 设置图片的宽度适应屏幕的大小
- (void)setWebViewHtmlImageFitPhone
{
CGFloat width = [[UIScreenmainScreen]bounds].size.width;

NSString *jsStr = [NSStringstringWithFormat:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth = '%f';" //自定义宽度
"for(i=0;i <document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){"
"oldwidth = myimg.width;"
"myimg.width = maxwidth;"
"}"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);",width];
[_webViewstringByEvaluatingJavaScriptFromString:jsStr];
[_webViewstringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(@"开始加载");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"加载完成");
[selfsetWebViewHtmlImageFitPhone];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullableNSError *)error
{
NSLog(@"加载失败 error == %@",error);
}

- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: