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:@"%@",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];
    
}

你可能感兴趣的:(iOS 处理HTML字符串,UIScrollView嵌套webView 获取webVeiw页面高度)