gitHub地址:GitHub - littleMeaning/SimpleWord: 模仿石墨文档文档编辑器,使用原生代码写的富文本编辑器,支持字体、颜色设置,支持缩进,列表、checkbox,支持插入图片等。 (*开发中)
- 在LMWordViewController中添加对象方法,传入编辑的html数据。
- 获取html数据中的图片
- (NSArray *) getImageurlFromHtml:(NSString *) webString
{
NSMutableArray * imageurlArray = [NSMutableArray arrayWithCapacity:1];
//标签匹配
NSString *parten = @"<img(.*?)>";
NSError* error = NULL;
NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:0 error:&error];
NSArray* match = [reg matchesInString:webString options:0 range:NSMakeRange(0, [webString length] - 1)];
for (NSTextCheckingResult * result in match) {
//过去数组中的标签
NSRange range = [result range];
NSString * subString = [webString substringWithRange:range];
//从图片中的标签中提取ImageURL
NSRegularExpression *subReg = [NSRegularExpression regularExpressionWithPattern:@"http://(.*?)\"" options:0 error:NULL];
NSArray* match = [subReg matchesInString:subString options:0 range:NSMakeRange(0, [subString length] - 1)];
NSTextCheckingResult * subRes = match[0];
NSRange subRange = [subRes range];
subRange.length = subRange.length -1;
NSString * imagekUrl = [subString substringWithRange:subRange];
//将提取出的图片URL添加到图片数组中
[imageurlArray addObject:imagekUrl];
}
return imageurlArray;
}
- 用把获取到的图片URL数组 替换一个个图片地址的null值
-(void)handlerAllAttechmentWith:(NSAttributedString *)attributedString withimagesArr:(NSArray*)imageUrl;
{
NSMutableArray *attachmentArr=[NSMutableArray array];
NSRange effectiveRange = NSMakeRange(0, 0);
while (effectiveRange.location + effectiveRange.length < attributedString.length) {
NSDictionary *attributes = [attributedString attributesAtIndex:effectiveRange.location effectiveRange:&effectiveRange];
NSTextAttachment *attachment = attributes[@"NSAttachment"];
if (attachment) {
[attachmentArr addObject:attachment];
}
effectiveRange = NSMakeRange(effectiveRange.location + effectiveRange.length, 0);
}
if (attachmentArr.count == imageUrl.count) {
for (int i=0; i<attachmentArr.count; i++) {
NSTextAttachment *att=attachmentArr[i];
att.attachmentType = LMTextAttachmentTypeImage;
att.userInfo=imageUrl[i];
}
}
}
网友评论
NSString *newString = [self.content stringByReplacingOccurrencesOfString:@"<img" withString:[NSString stringWithFormat:@"<img width=\"%f\"",LAScreenWidth - 40]];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[newString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType } documentAttributes:nil error:nil];
self.wordViewController.textView.attributedText = attributedString;
然后再去调上面的方法就好 。