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

iOS开发 专栏收录该内容
104 篇文章 2 订阅

#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


  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值