Вам необходимо перечислить 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]];
Спасибо. Я буду реализовывать данное решение и обновит вас. –
Большое спасибо за это. Даже если я устанавливаю свои собственные текстовые вложения, когда я пытаюсь их снова извлечь, 'image' равен нулю, но работает' imageForBounds'! Не так много информации, это похоже на ошибку. – Tim
@larme, как установить в метке –