iOS 富文本之圖文混排之編輯

插入圖片,上傳服務器 看這里
直接上代碼了。

1.把需要編輯的內容里面的照片過濾出來

- (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://[^'|\"|\\s|>]*" 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 ;
        
        NSString * imagekUrl = [subString substringWithRange:subRange];
        
        //將提取出的圖片URL添加到圖片數組中
        
        [imageurlArray addObject:imagekUrl];
        
    }
    
    return imageurlArray;
    
}

2.因為把html 轉成富文本(轉完之后 圖片attechment里面的userinfo是空的),所以需要給userinfo附上值,也就是上面獲取的image

- (void)handlerAllAttechmentWith:(NSAttributedString *)StringString withimagesArr:(NSArray *)imageUrl{
    
    NSMutableArray *attachmentArr=[NSMutableArray array];
    
    NSRange effectiveRange = NSMakeRange(0, 0);
    
    while (effectiveRange.location + effectiveRange.length < StringString.length) {
        
        NSDictionary *attributes = [StringString 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];
            
            //userinfo這個屬性是延展,看上一篇
            att.userInfo= imageUrl[i];
            
    
        }
        
    }
}

3.接下來的操作,按照插入圖片,上傳服務器走就可以。

在這里,只是簡單實現圖片的更換,文字的修改。涉及到字體大小,顏色等操作,后期慢慢加入。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容