美文网首页iOS知识专题iOS Developer
iOS开发UITextView富文本设置行距,颜色及插入图片

iOS开发UITextView富文本设置行距,颜色及插入图片

作者: wwwwwwww1 | 来源:发表于2017-05-26 10:43 被阅读125次

    1.设置行距和根据range设置颜色

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = kGetP(9);// 字体的行间距
    NSString *str1 = self.describeLab.text;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.describeLab.text];
    [str addAttribute:NSForegroundColorAttributeName value:kDescribeLabelColor range:NSMakeRange(0,4)];
    [str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str1   length])];
    self.describeLab.attributedText = str;
    

    2.插入图片附件

     NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = img;//[UIImage imageNamed:@"imageName"];
    attachment.bounds = CGRectMake(0, 0, kGetP(316.5), kGetP(148));
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = kGetP(5);// 字体的行间距
    NSMutableAttributedString *attachmentString = (NSMutableAttributedString *)[NSAttributedString attributedStringWithAttachment:attachment];
    [_textView.textStorage appendAttributedString:attachmentString];
    

    3.读取图片附件数据

    NSAttributedString *attStr = cell.textView.attributedText;
    
    NSMutableAttributedString *resutlAtt = [[NSMutableAttributedString alloc] initWithAttributedString:attStr];
    
    __block NSUInteger index = 1;
    //枚举出所有的附件字符串
    __block NSUInteger base = 0;
    [attStr enumerateAttributesInRange:NSMakeRange(0, attStr.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
    
        //NSTextAttachment value类型 key-NSAttachment 从字典中取得那一个图片
        //获取当前替换字符串的长度
        __block NSUInteger base = 0;
        NSTextAttachment *textAtt = attrs[@"NSAttachment"];
        WDLog(@"%@", textAtt.image);
        if (textAtt)
        {
            NSString *p = [NSString stringWithFormat:@"{{p%lu}}", (unsigned long)index];
            [resutlAtt replaceCharactersInRange:NSMakeRange(range.location + base, range.length)
                                     withString:p];
            base += p.length;
            index++;
        }  
          
    }];
    
    WDLog(@"---resutlAtt.string----- %@", resutlAtt.string);

    相关文章

      网友评论

        本文标题:iOS开发UITextView富文本设置行距,颜色及插入图片

        本文链接:https://www.haomeiwen.com/subject/iqitfxtx.html