我正在做的是:
- NSATTRIBUTE 字符串 = NSSTRING + UIIMAGE's;
- NSDATA = NSATTRIBUTED 字符串;
- 我还可以将 nsdata 转换为 nsattributed 字符串
- NSATTRIBUTEDSTRING = NSDATA:
- 然后从 NSAttributedstring 中提取嵌套
- NSSTRING = [NSATTRIBUTED STRING 字符串];
Query:
我如何从 NSATTRIBUTEDSTRING 获取图像;
- UIIMAGE = 来自 NSATTRIBUTEDSTRING;
- 图像数组 = 来自 NSATTRIBUTEDSTRING;
你必须枚举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]
将为零,您将无法获取图像。
您可以看到在此代码段中使用断点(通过设置真实图像 URL 和bundle 中的真实图像名称)。
NSString *htmlString = @"http://anImageURL\">Blahttp://anOtherImageURL\"> 测试retest";
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]];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)