iOS 处理HTML字符串,UIScrollView嵌套webView 获取webVeiw页面高度

最近做新闻详情页,后台返回的是HTML字符串,这里记录一下,顺便说一下UIScrollView嵌套webView 获取webVeiw页面高度,我的解决方案

直接上代码
//后台返回的HTML字符串
NSString *replaceStr = self.model.content; 

//去除字符串中的换行符和制表符(可有可无,看需求)
replaceStr = [replaceStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
replaceStr = [replaceStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];

 //拼接字符串,改变图片和文字的大小(使图片和文字实现自适应大小)
 NSString *htmlStr = [NSString stringWithFormat:@"<head><style>img{max-width:100%% !important;} table{max-width:100%% !important;}</style></head>%@",replaceStr];

//调用webView的方法
因为是UIScrollView嵌套webView,所以初始化webView的时候给一个高度就可以了,后面的代码会动态的获取webView的高度
[webView   loadHTMLString:htmlStr baseURL:nil];

//添加webView到UIScrollView上
[self.mainView addSubview:webView];

现在的话,图文加载基本没有问题了,下面来处理高度的问题

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

#pragma  make -- Kvo
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{
    
    if ([keyPath isEqualToString:@"contentSize"]) {
        
        //获取webview的内容高度
        
        self.webViewHeight = [[self.contentLabel stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
        
        //通过webview的contentSize获取内容高度
        
        //        self.webViewHeight = [self.showWebView.scrollView contentSize].height;
        
        CGRect newFrame = self.contentLabel.frame;
        
        newFrame.size.height= self.webViewHeight;
        
        NSLog(@"-document.body.scrollHeight-----%f",self.webViewHeight);
        
        NSLog(@"-contentSize-----%f",self.webViewHeight);
        
//在这里重新计算webView的frame
        self.webView.frame = CGRectMake(self.timeLabel.frame.origin.x, self.timeLabel.frame.origin.y + self.timeLabel.frame.size.height, self.titleLabel.frame.size.width, self.webViewHeight);

//在这里重新计算ScrollView的contentSize
        self.mainView.contentSize = CGSizeMake(kWidth, self.titleLabel.frame.size.height + 35 + self.webViewHeight);
    }
}
-(void)dealloc

{
    //移除监听者
    [self.contentLabel.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil];
    
}

复制代码

转载于:https://juejin.im/post/5a311bbdf265da4304069e21

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值