ios -WKWebView 高度 准确,留有空白的解决方案

本文介绍如何利用WKWebView加载天猫商品详情页面,并通过监听scrollView的contentSize变化来自动调整webView的高度。

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

 

#import "ViewController.h"

#import <WebKit/WebKit.h> 

@interface ViewController ()<WKNavigationDelegate>

@property (nonatomic, strong)WKWebView *webView;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad

{

    _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 1)];

    _webView.UIDelegate = self;

    _webView.navigationDelegate = self;

    [self.view addSubview:_webView];

    NSString *url = [NSString stringWithFormat:@"https://mdetail.tmall.com/templates/pages/desc?id=13128565333"];

    NSLog(@"dfurk:%@",url);

    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]]];

 

    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

}

 

- (void)dealloc {

    

    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil];

}

 

- (void)observeValueForKeyPath:(NSString *)keyPath

                      ofObject:(id)object

                        change:(NSDictionary *)change

                       context:(void *)context

{

    if (object == self.webView.scrollView && [keyPath isEqual:@"contentSize"]) {

        // we are here because the contentSize of the WebView's scrollview changed.

        

        UIScrollView *scrollView = self.webView.scrollView;

        self.webView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);

        NSLog(@"New contentSize: %f x %f", scrollView.contentSize.width, scrollView.contentSize.height);

    }

}

/*

#pragma mark - Navigation

 

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

 

@end

转载于:https://www.cnblogs.com/shenlaiyaoshi/p/8676622.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值