我正在做的是:
询问:
如何从NSATTRIBUTED STRING获取图像;
您必须枚举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 \“>测试复试”;
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]];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句