iOS加载Html文本

UILable||UITextView加载html

使用UILable或TextView比较方便,但是字体样式无法保证,推荐使用下面的UIWebView加载

UITextView *titleTexV;

- (void)setTitleStr:(NSString *)titleStr{
    _titleStr = titleStr;
    
    //添加行间距,不过没用
    self.attriStr = [self setHotSpotWithString:_titleStr];
    
    //赋值
    self.titleTexV.attributedText = self.attriStr;
    
    //计算html文本高度
    CGFloat desHeight =  [self.attriStr boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;
    self.footerDesHeight = 50+desHeight;
    
    //更新布局
    [_titleTexV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(desHeight);
    }];
    
}

//添加行间距等样式
- (NSMutableAttributedString *)setHotSpotWithString:(NSString *)str{
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:4*layoutBy6()];
    NSDictionary *attDic = @{NSFontAttributeName : [UIFont systemFontOfSize:12*layoutBy6()],
                             NSParagraphStyleAttributeName : paragraphStyle,
                             NSForegroundColorAttributeName:hexStringToColor(@"999999"),
                             NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType
                             };
    
    NSMutableAttributedString *lastStr = [[NSMutableAttributedString alloc]initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:attDic documentAttributes:nil error:nil];
    return lastStr;
}
WebView加载

参考我之前的文章:UITableViewCell嵌套UIWebView

typedef void(^DescriptionBlock)(void);

@property (nonatomic , copy) NSString *desStr;         //赋值的Html文本

@property (nonatomic , assign) CGFloat cellHeight;       //需要返回给View的

@property (nonatomic , copy) DescriptionBlock myBlock;   //Block回调

/-----------------------------------------------------------------------/



- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //加载完成后获取WebView实际高度
    CGFloat webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, webViewHeight);
    //赋值并回调需要的cellHeight
    self.cellHeight = webViewHeight;
    if (self.myBlock) {
        self.myBlock();
    }
}

-(void)setDesStr:(NSString *)desStr {
    _desStr = desStr;
    //移除所有视图
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //添加WebView 注:这里的Frame高度必须赋值
    UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    webView.scrollView.scrollEnabled = NO;
    webView.delegate =self;
    [webView sizeToFit];
    [self addSubview:webView];
    //加载Html文件
    [webView loadHTMLString:desStr baseURL:nil];
}

//外部调用:
- (ChooseGradeFooterDesView *)footerDesV{
    if (!_footerDesV) {
        _footerDesV = [[ChooseGradeFooterDesView alloc]init];
        __weak typeof(self) weakSelf = self;
        _footerDesV.myBlock = ^{
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        };
    }
    return _footerDesV;
}

其它关于计算文本高度 || 正则去除标签的方法

//计算文本size
- (CGSize)getSizeWithStr:(NSString *)str Font:(float)font viewWidth:(CGFloat)widht{
    
    NSString *string = [self getZZwithString:str];
    //加行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:4*layoutBy6()];
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:font], NSParagraphStyleAttributeName:paragraphStyle};
    
    CGSize sizeO = [string boundingRectWithSize:CGSizeMake(widht, 20000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    
    return sizeO;
}

//正则去除网络标签
-(NSString *)getZZwithString:(NSString *)string{
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n"
                                                                                    options:0
                                                                                      error:nil];
    string=[regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];
    return string;
}

参考文章

你可能感兴趣的:(iOS加载Html文本)