我有一个NSAttributedString
,可以包含3个不同的内容:
我试图"扫描"那个对象要知道我是否有图像或文本,如果有图像,如果之后有文字。
我不习惯使用枚举和范围参数;文档并没有真正帮助我理解如何使这项工作。
你将如何实现这一目标?
我现在唯一的代码是来自另一个SO帖子,如果只有一张图片,它会很有帮助。
NSAttributedString *currentString = self.inputToolbar.contentView.textView.attributedText;
__block UIImage *currentImage = nil;
[currentString enumerateAttribute:NSAttachmentAttributeName
inRange:NSMakeRange(0, [currentString 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)
currentImage = image;
}
}];
答案 0 :(得分:0)
我们的想法是保持相同的逻辑,但使用NSMutableAttributedString
代替NSAttributedString
,保留图片的NSRange
并删除它。
NSMutableAttributedString *currentString = [[NSMutableAttributedString alloc] initWithAttributedString:self.inputToolbar.contentView.textView.attributedText];
__block UIImage *currentImage = nil;
__block NSRange imageRange;
[currentString enumerateAttribute:NSAttachmentAttributeName
inRange:NSMakeRange(0, [currentString 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)
{
currentImage = image;
imageRange = range;
}
}
}];
NSString *text = @"";
if (image)
{
text = [[currentString deleteCharactersInRange:imageRange] string];
}
if ([text length] > 0)
{
NSLog(@"Found Text: %@", text);
}
else
{
NSLog(@"Did Found Text");
}
NSLog(image?@"Found Image";@"Did NOT found image");