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

来源:互联网 发布:商场广播软件 编辑:程序博客网 时间:2024/04/30 14:56

#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


0 0
原创粉丝点击