wkwebview加载html的富文本(文字和图片混合)

tableHeaderView上加载wkwebView作为头部视图并更新高度

//
//  ViewController.m
//  WKWebViewDemo
//
//  Created by Mac xk on 2019/10/25.
//  Copyright © 2019 Mac xk. All rights reserved.
//

#import "ViewController.h"
#import 
#import "XKInformationHeaderView.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)XKInformationHeaderView *headView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tabHeightCons;

@end

@implementation ViewController
-(XKInformationHeaderView *)headView{
    if (!_headView) {
        _headView=[[[NSBundle mainBundle]loadNibNamed:@"XKInformationHeaderView" owner:self options:nil]firstObject];
        _headView.frame = [UIScreen mainScreen].bounds;
    }
    
    return _headView;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.tableView.tableHeaderView = self.headView;
    self.headView.webHeightBlock = ^(CGFloat webH) {
    self.tabHeightCons.constant = webH+80+(([UIScreen mainScreen].bounds.size.width-22)*240/353);
//    self.headView.frame.size.height = self.tabHeightCons.constant;
         [self.tableView beginUpdates];
         [self.tableView setTableHeaderView:self.headView] ;
         [self.tableView endUpdates];
    };
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}



- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

     return 0.01;

    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{

    return 0.01;
    
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 0.01;
    
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"topicCellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell ) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    return cell;
}


@end

tableHeaderView类

精准计算WKWebView中html内容高度的方法
#import 

NS_ASSUME_NONNULL_BEGIN

@interface XKInformationHeaderView : UIView
@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@property (assign, nonatomic)CGFloat headerHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *webVHeightCons;
@property(copy,nonatomic)void(^webHeightBlock)(CGFloat);
@end

NS_ASSUME_NONNULL_END
//
//  XKInformationHeaderView.m
//  eResidents
//
//  Created by Mac xk on 2019/9/17.
//  Copyright © 2019 Jon Shi. All rights reserved.
//

#import "XKInformationHeaderView.h"
#import 

@interface XKInformationHeaderView ()
@property (weak, nonatomic) IBOutlet UIView *imgV;
@property (weak, nonatomic) IBOutlet UILabel *titleLab;
@property (weak, nonatomic) IBOutlet UILabel *readLab;
@property (weak, nonatomic) IBOutlet UILabel *contentlab;
@property (weak, nonatomic) IBOutlet UIButton *shoucangBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLab;
@property (strong, nonatomic) WKWebView *contenWebV;
@property (weak, nonatomic) IBOutlet UIView *backV;

@end
@implementation XKInformationHeaderView

-(void)awakeFromNib
{
    [super awakeFromNib];
      WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
     WKPreferences *preferences = [[WKPreferences alloc]init];

     preferences.javaScriptCanOpenWindowsAutomatically = true;

     //    图片自适应高度
     NSString *jSString = @"var objs = document.getElementsByTagName('img');for(var i=0;i++){var img = objs[i];img.style.maxWidth = '100%';img.style.height='auto';}";

     WKUserScript *wkUserScript = [[WKUserScript alloc]initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

     //    修改文字大小
     NSString*jScript =@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

     WKUserScript *wkScript = [[WKUserScript alloc]initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
     WKUserContentController *ucontroller = [[WKUserContentController alloc]init];
     [ucontroller addUserScript:wkUserScript];
     [ucontroller addUserScript:wkScript];
     configuration.preferences = preferences;
     WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [UIScreen mainScreen].bounds.size.width, 0) configuration:configuration];
     NSString * htmlString = @"<p style=\"white-space: normal; text-align: center;\"><img src=\"http://main.xiekang.net/Scripts/ueditor1_4_3_3-utf8-net/utf8-net/net/upload/image/20180228/6365541345806039683723703.jpg\" title=\"1.jpg\" alt=\"1.jpg\"/></p><p style=\"white-space: normal;\"><img src=\"http://main.xiekang.net/Scripts/ueditor1_4_3_3-utf8-net/utf8-net/net/upload/image/20180228/6365541346671664682702027.jpg\" title=\"2.jpg\" alt=\"2.jpg\"/></p><p style=\"white-space: normal;\"><img src=\"http://main.xiekang.net/Scripts/ueditor1_4_3_3-utf8-net/utf8-net/net/upload/image/20180228/6365541348234164683642219.jpg\" title=\"3.jpg\" alt=\"3.jpg\"/></p><p style=\"white-space: normal;\"><img src=\"http://main.xiekang.net/Scripts/ueditor1_4_3_3-utf8-net/utf8-net/net/upload/image/20180228/6365541349057602186791886.jpg\" title=\"4.jpg\" alt=\"4.jpg\"/></p><p style=\"white-space: normal;\"><img src=\"http://main.xiekang.net/Scripts/ueditor1_4_3_3-utf8-net/utf8-net/net/upload/image/20180228/6365541349673227181637951.jpg\" title=\"5.jpg\" alt=\"5.jpg\"/></p><p><br/></p>";
     wkWebView.scrollView.bounces = NO;
     wkWebView.navigationDelegate = self;
     [wkWebView loadHTMLString:[self setAttributedString:htmlString].string baseURL:nil];
    [self.backV addSubview:wkWebView];

}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError *_Nullable error) {
        //获取页面高度
        CGFloat height = [result doubleValue];
        NSLog(@"scrollHeight 即为所求:%f",height);
        webView.frame = CGRectMake(0, 91, [UIScreen mainScreen].bounds.size.width-22, height);
        self.webVHeightCons.constant = height;
          self.headerHeight = self.webVHeightCons.constant;
          if (self.webHeightBlock) {
              self.webHeightBlock(self.webVHeightCons.constant);
          }
        [self layoutIfNeeded];

        [self setNeedsLayout];
    }];
}

-(NSMutableAttributedString *)setAttributedString:(NSString *)str
{
    //如果有换行,把\n替换成
//如果有需要把换行加上 str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"
"]; //设置HTML图片的宽度 str = [NSString stringWithFormat:@"%@",[UIScreen mainScreen].bounds.size.width,str]; NSMutableAttributedString *htmlString =[[NSMutableAttributedString alloc] initWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:NULL error:nil]; // //设置富文本字的大小 // [htmlString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(0, htmlString.length)]; // //设置行间距 // NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; // [paragraphStyle setLineSpacing:5]; // [htmlString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [htmlString length])]; return htmlString; } //-(void)setModel:(XKInfoEntityMod *)model //{ // _model = model; // self.titleLab.text = model.wikiName; // CGRect frame = CGRectMake(0, 91, KScreenWidth-22,0); // frame.size.height = 0; // self.contenWebV.frame = frame; // [self.contenWebV loadHTMLString:[self setAttributedString:model.content].string baseURL:nil]; // //} - (IBAction)soucangAction:(id)sender { } @end

你可能感兴趣的:(wkwebview加载html的富文本(文字和图片混合))