iOS加载Html文本

本文详细介绍如何使用UIWebView在iOS应用中加载HTML文本,包括调整行间距、字体大小及颜色,以及通过JavaScript获取WebView的实际高度。同时,提供计算文本高度和去除HTML标签的实用方法。

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

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回调

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

<UIWebViewDelegate>

- (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;
}

参考文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值