webView 内容自适应 img

在处理后台返回的HTML内容时,遇到在iOS的WKWebView中图片无法自适应的问题。尝试了网上的一些解决方案未果,最终通过与H5开发协作,获取图片尺寸并结合屏幕缩放实现了图片自适应,并禁止用户手动缩放,确保内容居中展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近遇到了一个后台不负责任,发过来的html  在ios端就是展示的不能自适应

从网上搜的方法

WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        WKPreferences *perfrcen = [[WKPreferences alloc]init];
        perfrcen.javaScriptCanOpenWindowsAutomatically = YES;
        wkWebConfig.userContentController = wkUController;
        NSMutableString *JSString = [NSMutableString string];
        NSString *windowLocationString =  @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        [JSString appendString:windowLocationString];
       
//        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        
//        [JSString appendString:jSString];
        WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:JSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        /** << 添加js调用 > */
        wkWebConfig.preferences = perfrcen;
        [wkUController addUserScript:wkUserScript];
        _webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:wkWebConfig];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.opaque = NO;
        _webView.scrollView.scrollEnabled = NO;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        if (@available(iOS 11.0,*)) {
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }

这个并没有解决,我们要求返回了图片的size之后,还要跟屏幕缩放,几番周转 ,问了H5的朋友

- (NSString *)reSizeImageWithHTML:(NSString *)html {
    return [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><style type='text/css'>img{width: auto !important;height: auto; !important;max-width: 100%%;display: block;margin: 0 auto;}</style>%@", html];
}

这个方法将html拼接之后,就可以正常展示了 后面的是 图片自适应,然后居中,直接规定用户不能缩放。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值