用UITextView解析Html点击内容默认选中两个逗号之间的内容,并实现图文混排,自定义调整html 中图片的大小,点击图片可以取出其中的图片

Html的解析可以用MKwebView或者用UIwebView但是如果我们想要选中一些内容,用UItextview比较简单,先看一下运行结果:


用UitextView解析Html的关键的代码:

1.用富文本解析后台返回的数据,后台返回的是一堆Html的标签


//html 转化为普通文本

- (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString

{

    //    //转换参数

    //    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };

    //将html文本转换为正常格式的文本

    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

    //以下三个设置其实不是必要的,只是为了让解析出来的html文本更好看。

    //设置段落格式

    NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];

    //设置两端对齐

    para.alignment = NSTextAlignmentJustified;

    para.lineSpacing = 10;

    //para.paragraphSpacing = 10;

    [attStr addAttribute:NSParagraphStyleAttributeName value:para range:NSMakeRange(0, attStr.length)];

    //    //颜色

    //    [attStr addAttribute:NSForegroundColorAttributeName

    //                   value:UIColorFromRGB(0x3d3d3d)

    //                   range:NSMakeRange(0, attStr.length)];

    //字体

    [attStr addAttribute:NSFontAttributeName

                   value:[UIFont systemFontOfSize:15]

                   range:NSMakeRange(0, attStr.length)];


    return attStr;

}

由于需要选中点击内容的两个逗号直接的内容,所以需要自定义UItextview

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender

{

    NSRange range = [self selectedRange];

    NSString *str = nil;

    str = [self.attributedText.string substringWithRange:range];

    NSString *show = [self getContentduo:str];

    if (show.length < 5) {

        if ([str containsString:@"。"]) {

            NSArray *arrays = [str componentsSeparatedByString:@"。"];

            str = arrays[0];

        }

        NSArray *array = [self.attributedText.string componentsSeparatedByString:@"。"];

        int index = 0;

        for (int i = 0; i < array.count;  i++) {

            NSString *contnt = [self getContentduo:array[i]];

            if ([contnt containsString:str]) {

                index = i;

                // NSLog(@"%@",array[i]);

                NSRange range2 = [self.attributedText.string rangeOfString:[contnt stringByAppendingString:@"。"]];

                if ( range.location - range2.location < contnt.length || range.location - range2.location == contnt.length) {

                    self.selectedRange  = range2;

                    break;

                }

            }

            //由于存在图片,靠近图片选择的时候会出现不能准确判断位置的问题

            if (i == array.count - 1) {

                [self lastSet:array contnt:str];

            }


        }

    }

    //屏蔽了除复制以外的功能

    if (action == @selector(copy:)||action == @selector(shareSinas:)||action == @selector(shareSina:)) {

        return YES;

    }else{


        return NO;

    }


}

把逗号之间的内容分割,存到数组中

这个方法可以得到点击的时候点击文字的位置和内容,通过拿到点击的位置来判断该文字所在的字符串的位置,然后在改变选中的范围。

3. 如果后台没有对图片进行处理显示图片的时候会出现如下问题,图片显示原有的尺寸,但是不是我们所希望的,为此我们需要拼接一段字符串来改变图片的样式



第一种方法是拼接一个样式标签在返回值的前面

第二种方法是获取NSTextAttachment的对象。获取原图的大小,然后在改变其大小,返回值不做改变


两种方法都可以正确调整显示

3.取出图片

//获取图片的位置

- (void)textViewImageLocation{

    [self.attributedText enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, self.attributedText.string.length)

                                    options:0

                                 usingBlock:^(NSTextAttachment *value, NSRange range, BOOL *stop) {


                                     if (value) {

                                         NSLog(@"%@    %@",value , NSStringFromRange(range));

                                         [self.dict setValue:value forKey:NSStringFromRange(range)];


                                     }

                                 }];



}

#判断点的点是否是图片,让后从字典中找出图片

- (void)touchesBegan:(NSSet *)touches withEvent:(nullable UIEvent *)event{

    [super touchesBegan:touches withEvent:event];

    // 获取当前触摸位置的字符所属的字母(提示:触摸位置需向下调整10个点,以便与文本元素对齐)

    UITouch *touch = [touches anyObject];

    CGPoint touchPoint = [touch locationInView:self];

    touchPoint.y -= 10;

    // 获取点击的字母的位置

    NSInteger characterIndex = [self.layoutManager characterIndexForPoint:touchPoint inTextContainer:self.textContainer fractionOfDistanceBetweenInsertionPoints:NULL];


    // 获取单词的范围。range 由起始位置和长度构成。

    NSRange range = [self getWordRange:characterIndex];


    NSLog(@"---%@",NSStringFromRange(range));


    NSTextAttachment *value    =     [self.dict valueForKey:NSStringFromRange(range)];

    if (value) {

        if ([self.delegates respondsToSelector:@selector(getContentSelected:)]) {

            [self.delegates getContentSelected:value];

        }

    }

    //[self setBackgroundHighlighted:YES];

}

显示点击的图片

-(void)getContentSelected:(NSTextAttachment *)attach{


    [self.view addSubview:self.label];


    NSMutableAttributedString *textAttrStr = [[NSMutableAttributedString alloc] init];

   // attach.image = [UIImage imageNamed:@"bankcard_icon"];

    attach.bounds = CGRectMake(0, 0 , 100, 100);

    NSAttributedString *imgStr = [NSAttributedString attributedStringWithAttachment:attach];

    [textAttrStr appendAttributedString:imgStr];

    self.label.attributedText = textAttrStr;

}


Demo地址https://github.com/1546461417/ios-Html

你可能感兴趣的:(用UITextView解析Html点击内容默认选中两个逗号之间的内容,并实现图文混排,自定义调整html 中图片的大小,点击图片可以取出其中的图片)