2015-03-19 2 views
4

Что я делаю:Экстракт UIImage из NSAttributed Строка

  1. NSATTRIBUTE STRING = NSString + UIImage-х;
  2. NSDATA = NSATTRIBUTED STRING;
  3. ТАКЖЕ Я могу преобразовать NSData в nsattributed строку
  4. NSATTRIBUTED STRING = NSData:
  5. А затем извлекая гнездования из NSAttributed строки
  6. NSString = [NSATTRIBUTED СТРОКА];

Запрос:

Как я могу получить изображения из NSATTRIBUTED STRING;

  • UIIMAGE = от NSATTRIBUTED STRING;
  • ARRAYOFIMAGE = от NSATTRIBUTED STRING;

ответ

14

Вам необходимо перечислить NSAttributedString, чтобы найти NSTextAttachment s.

NSMutableArray *imagesArray = [[NSMutableArray alloc] init]; 
[attributedString enumerateAttribute:NSAttachmentAttributeName 
          inRange:NSMakeRange(0, [attributedString length]) 
          options:0 
          usingBlock:^(id value, NSRange range, BOOL *stop) 
{ 
    if ([value isKindOfClass:[NSTextAttachment class]]) 
    { 
    NSTextAttachment *attachment = (NSTextAttachment *)value; 
    UIImage *image = nil; 
    if ([attachment image]) 
     image = [attachment image]; 
    else 
     image = [attachment imageForBounds:[attachment bounds] 
          textContainer:nil 
          characterIndex:range.location]; 

    if (image) 
     [imagesArray addObject:image]; 
    } 
}]; 

Как вы можете видеть, есть тест if ([attachment image]). Это потому, что кажется, что если вы создали NSTextAttachment, чтобы положить его с NSAttachmentAttributeName, он будет существовать, и ваше изображение будет там. Но если вы используете, например, изображение из Интернета и конвертируете его как NSTextAttachment из HTML-кода, то [attachment image] будет nil, и вы не сможете получить изображение.

Вы можете увидеть с помощью контрольных точек с этим фрагментом (с установкой реального URL изображения и реальное имя изображения из пучка NSString * HTMLString = @. "HTTP: // anImageURL \"> Blahttp: // anOtherImageURL \ "> Test повторного тестирование «;

NSError *error; 
NSAttributedString *attributedStringFromHTML = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] 
                       options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, 
                          NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)} 
                    documentAttributes:nil 
                        error:&error]; 

NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init]; 
[textAttachment setImage:[UIImage imageNamed:@"anImageNameFromYourBundle"]]; 

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedStringFromHTML]; 
[attributedString appendAttributedString:[NSAttributedString attributedStringWithAttachment:textAttachment]]; 
+0

Спасибо. Я буду реализовывать данное решение и обновит вас. –

+0

Большое спасибо за это. Даже если я устанавливаю свои собственные текстовые вложения, когда я пытаюсь их снова извлечь, 'image' равен нулю, но работает' imageForBounds'! Не так много информации, это похоже на ошибку. – Tim

+0

@larme, как установить в метке –

4

в Swift 3: (с MacOS эквивалентной here)

func textViewDidChange(_ textView: UITextView) { 

    // other code... 

    let range = NSRange(location: 0, length: textView.attributedText.length) 
    if (textView.textStorage.containsAttachments(in: range)) { 
     let attrString = textView.attributedText 
     var location = 0 
     while location < range.length { 
      var r = NSRange() 
      let attrDictionary = attrString?.attributes(at: location, effectiveRange: &r) 
      if attrDictionary != nil { 
       // Swift.print(attrDictionary!) 
       let attachment = attrDictionary![NSAttachmentAttributeName] as? NSTextAttachment 
       if attachment != nil { 
        if attachment!.image != nil { 
         // your code to use attachment!.image as appropriate 
        } 
       } 
       location += r.length 
      } 
     } 
    } 
} 
3

Я преобразованный код Larme к быстрым 3

 var imagesArray = [Any]() 

     textView.attributedText.enumerateAttribute(NSAttachmentAttributeName, in: NSRange(location: 0, length: textView.attributedText.length), options: [], using: {(value,range,stop) -> Void in 
      if (value is NSTextAttachment) { 
       let attachment: NSTextAttachment? = (value as? NSTextAttachment) 
       var image: UIImage? = nil 

       if ((attachment?.image) != nil) { 
        image = attachment?.image 
       } else { 
        image = attachment?.image(forBounds: (attachment?.bounds)!, textContainer: nil, characterIndex: range.location) 
       } 

       if image != nil { 
        imagesArray.append(image) 
       } 
      } 
     }) 
Смежные вопросы