iOS富文本编辑器

富文本编辑器采坑,继承一下UITextView

UITextView 属性:typingAttributes 实时改变输入文字的样式

比如设置下划线:


- (void)setUnderLine:(BOOL)UnderLine{
    _UnderLine = UnderLine;
    self.attributes[NSUnderlineStyleAttributeName] = (_UnderLine?@1:@0);
    
    self.typingAttributes = self.attributes;
}

改变光标位置:

self.selectedRange  = NSMakeRange(rg.location+1, 0);
    [self scrollRangeToVisible: self.selectedRange];

把html转为 NSAttributedString 的方法。

   NSDictionary *options = @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                               NSFontAttributeName:[UIFont systemFontOfSize:15],
                               NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]
                               };
    NSData *data = [contetn dataUsingEncoding:NSUnicodeStringEncoding];
    NSAttributedString *att = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];

此处 contetn为html字符串。

这里额外需要做的工作就是从html中提取image 。一般是链接,然后通过sdwebimage 请求,

从html 中过滤出 image 标签,

- (NSArray *)filterImageUrlFromHTML:(NSString *)html
{
    if (!html) {
        return @[];
    }
    NSMutableArray *resultArray = [NSMutableArray array];
    
    static NSRegularExpression *regex = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *pattern = @"<(img|IMG)(.*?)(/>|></img>|>)";
        regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    });
    
    NSArray *result = [regex matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(0, html.length)];
    
    for (NSTextCheckingResult *item in result) {
        @autoreleasepool {
            NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:0]];
            
            NSArray *tmpArray = nil;
            if ([imgHtml rangeOfString:@"src=\""].location != NSNotFound) {
                tmpArray = [imgHtml componentsSeparatedByString:@"src=\""];
            } else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
                tmpArray = [imgHtml componentsSeparatedByString:@"src="];
            }
            
            if (tmpArray.count >= 2) {
                NSString *src = tmpArray[1];
                
                NSUInteger loc = [src rangeOfString:@"\""].location;
                if (loc != NSNotFound) {
                    src = [src substringToIndex:src.length];
                    [resultArray addObject:src];
                }
            }
        }
    }
    
    return resultArray;
}

接下来,通过enumerateAttributesInRange遍历 NSAttributedString找出图片,替换掉,就OK了。

通过 遍历NSAttributedString生成html字符串的方法,遍历富文本,添加标签。方法如下:

- (NSString*)getHtmlEdit:(NSArray *)arr {
    __block NSMutableString *htmlString = @"<p>".mutableCopy;
    
    //枚举出所有的附件字符串-这个是顺序来的NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
    [self enumerateAttributesInRange:NSMakeRange(0, self.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *Attributes, NSRange range, BOOL *stop) {
        
        //1.  通过range取出相应的字符串
        NSString * title = [self.string substringWithRange:range];
        
        CGNSTextAttachment * att = Attributes[@"NSAttachment"];
        
        if (att) {
            CGSize  imgSize = att.image.size;
            CGFloat newImgW = imgSize.width;
            CGFloat newImgH = imgSize.height;
            CGFloat textW   = SCREEN_WIDTH - (30);
            if (newImgW > textW) {
                CGFloat ratio = textW / newImgW;
                newImgW  = textW;
                newImgH *= ratio;
            }

            CGNSTextAttachment *attachment = [[CGNSTextAttachment alloc]initWithData:nil ofType:nil];
            attachment.image = [UIImage imageNamed:@""];
            attachment.bounds = CGRectMake(0, 0, newImgW, newImgH);
            attachment.imageUrl = @"";
            attachment.w = newImgW;
            attachment.h = newImgH;



            NSLog(@"imageUrl ====  %@", att.imageUrl);
        }
        
        if ([title containsString:@"\n"]) {
            NSString* relpaceString = [title stringByReplacingOccurrencesOfString:@"\n" withString:@"<br>"];
            [htmlString appendString:relpaceString];
        }else if(att){
            [htmlString appendString:@"</p>"];
            [htmlString appendString:[NSString stringWithFormat:@"<img src=\"%@\" height=\"%.f\" width=\"%.f\">",att.imageUrl,att.h,att.w]];
            [htmlString appendString:@"<p>"];
        }else{
            //1,是否加粗
            NSString *bold = Attributes[@"NSStrokeWidth"];
            UIFont * font= Attributes[@"NSFont"];
            
            BOOL isBlold = NO;
            if (font) {
                NSString* name = font.fontDescriptor.postscriptName;
                if (name.length && [name.lowercaseString containsString:@"bold"]) {
                    isBlold = YES;
                }
            }
            
            if ([bold integerValue] <0.0 || isBlold) {
                [htmlString appendString:@"<b>"];
            }
            //是否斜体
            NSString *obliq = Attributes[@"NSObliqueness"];
            if ([obliq floatValue] > 0.0) {
                [htmlString appendString:@"<i>"];
            }
            //是否下划线
            NSString *NSUnderline = Attributes[@"NSUnderline"];
            if ([NSUnderline integerValue] > 0.0) {
                [htmlString appendString:@"<u>"];
            }
            //是否删除线
            NSString *NSdeleateline = Attributes[@"NSUnderlineStyleSingle"];
            if ([NSdeleateline integerValue] > 0.0) {
                [htmlString appendString:@"<s>"];
            }
            
            
            [htmlString appendString:@"<font "];
            
            //2.颜色
            UIColor * fontColor= Attributes[@"NSColor"];
            if (fontColor) {
                [htmlString appendString:[NSString stringWithFormat:@"color='%@'",[self HEXString:fontColor]]];
            }
            
            //3.字体
            if (font) {
                CGFloat size = font.fontDescriptor.pointSize;
                [htmlString appendString:[NSString stringWithFormat:@" style='font-size:%.fpx;'",size]];
            }
            [htmlString appendString:@">"];
            
            NSRange range = [title rangeOfString:@" "];
            if (range.location != NSNotFound) {
                NSUInteger leng = [title length];
                NSString *temp = [NSString string];
                for (int i=0; i<leng; i++) {
                    temp = [temp stringByAppendingString:@"&nbsp;"];
                }
                [htmlString appendString:temp];
            }else{
//                UIColor * bgColor= Attributes[@"NSBackgroundColor"];
//                if (bgColor) {
//                    [htmlString appendString:[NSString stringWithFormat:@"<span style=\"background-color: %@;\">%@</span>",[self HEXString:bgColor],title]];
//                }else{
                    [htmlString appendString:title];
//                }
            }
            
            [htmlString appendString:@"</font>"];
            
            
            if ([NSdeleateline integerValue] > 0.0) {
                [htmlString appendString:@"</s>"];
            }
            
            if ([NSUnderline integerValue] > 0.0) {
                [htmlString appendString:@"</u>"];
            }
            
            if ([obliq floatValue] > 0.0) {
                [htmlString appendString:@"</i>"];
            }
            if ([bold integerValue] < 0.0 || isBlold) {
                [htmlString appendString:@"</b>"];
            }
        }
    }];
    
    [htmlString appendString:@"</p>"];
    
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"<p></p>" withString:@""].mutableCopy;
    NSLog(@"%@",htmlString);
    
    return htmlString;
    
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容