iOS与Html富文本(纯文本)的那点事

直接将富文本转成普通文本展示

//将Html字符串转成OC的富文本对象
NSAttributedString *attStr = [[NSAttributedString alloc] initWithData:@"你想解析的html字符串" dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
//resultStr 就是我们要的普通字符串
NSString * resultStr=attStr.string;

通过原生控件的attributedText属性展示

label.attributedText = attStr;
textField.attributedText=attStr;
textView.attributedText=attStr;

计算富文本的高度

+ (CGFloat)getStrHeightWithAttributeStr:(NSAttributedString *)string
                                    viewWidth:(CGFloat)viewWidth{
    if (string.length == 0) {
        return 0;
    }
     CGSize size  = [string boundingRectWithSize:CGSizeMake(viewWidth, MAXFLOAT) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  context:nil].size;
    return ceil(size.height);
}

计算富文本的长度

+ (CGFloat)getStrWidthWithAttributeStr:(NSAttributedString *)string
                                  viewHeight:(CGFloat)viewHeight{
    if (string.length == 0) {
        return 0;
    }
    CGSize size  = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, viewHeight) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    return ceil(size.width);
}

UILabel实现点击文字跳链效果(有相关需求的可以参照一下,编程思路应该是一致的)

1.获取用户点击事件

我这里是子类化一个label,在其初始化的方法里添加了一个单击手势

@interface LSHtmlLabel ()
@property (nonatomic,strong)NSTextStorage *textStorage;
@property (nonatomic,strong)NSLayoutManager *layoutManager;
@property (nonatomic,strong)NSTextContainer *textContainer;
@end 

@implementation LSHtmlLabel
-(instancetype)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self)
    {
        self.userInteractionEnabled=YES;
        self.numberOfLines=0;
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [self addGestureRecognizer:tap];
        self.textStorage = [NSTextStorage new];
        self.layoutManager = [NSLayoutManager new];
        self.textContainer = [NSTextContainer new];
        [self.textStorage addLayoutManager:self.layoutManager];
        [self.layoutManager addTextContainer:self.textContainer];
    }
    return self;
}

2.通过事件获取用户点击的在UILabel上的位置,通过计算得出用户点击的文字及文字的下标

-(void)tapClick:(UITapGestureRecognizer * )gesture
{
    CGPoint location=[gesture locationInView:self];
    self.textContainer.size = self.bounds.size;
    self.textContainer.lineFragmentPadding = 0;
    self.textContainer.maximumNumberOfLines = self.numberOfLines;
    self.textContainer.lineBreakMode = self.lineBreakMode;
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    NSRange textRange = NSMakeRange(0, attributedText.length);
    [attributedText addAttribute:NSFontAttributeName value:self.font range:textRange];
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.alignment = self.textAlignment;
    [attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:textRange];
    [self.textStorage setAttributedString:attributedText];
       
        
    CGSize textSize = [self.layoutManager usedRectForTextContainer:self.textContainer].size;
        //    location.x -= (CGRectGetWidth(self.label.frame) - textSize.width) / 2;
        location.y -= (CGRectGetHeight(self.frame) - textSize.height) / 2;
        
    NSUInteger glyphIndex = [self.layoutManager glyphIndexForPoint:location inTextContainer:self.textContainer];
    CGFloat fontPointSize = self.font.pointSize;
    [self.layoutManager setAttachmentSize:CGSizeMake(fontPointSize, fontPointSize) forGlyphRange:NSMakeRange(self.text.length - 1, 1)];
    NSAttributedString *attributedSubstring = [self.attributedText attributedSubstringFromRange:NSMakeRange(glyphIndex, 1)];
    CGRect glyphRect = [self.layoutManager boundingRectForGlyphRange:NSMakeRange(glyphIndex, 1)
                                                                    inTextContainer:self.textContainer];
    if (!CGRectContainsPoint(glyphRect, location)) {
        if (CGRectContainsPoint(CGRectMake(0, 0, textSize.width, textSize.height), location)) {
        }
        NSLog(@"没找到呢,该怎么办才好呢");
        return;
    }    
    //此处我通过block块返回的两个值
    _clickLabelBlock(self,(unsigned long)glyphIndex,attributedSubstring);  
}

3.拿到用户点击的文字下标,富文本文字此时你就可以为所欲为啦

  LSHtmlLabel * label=[[LSHtmlLabel alloc]initWithFrame:_htmlLabel.frame];
    [label setClickLabelBlock:^(LSHtmlLabel * _Nonnull label, NSUInteger index, NSAttributedString * _Nonnull attributedSubstring) {
        NSLog(@"%@",attributedSubstring);
        //获取文字属性字典
        NSRange range = NSMakeRange(0, 1);
        NSDictionary*dic = [attributedSubstring attributesAtIndex:0 effectiveRange:&range];
        //判断超链接是否存在 添加对应的处理逻辑
        if (dic[@"NSLink"])
        {
            NSLog(@"%@",dic[@"NSLink"]);
        }        
    }];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容