我有一个NSAttributedString,它可以包含3种不同的东西:
我试图“扫描”该对象,以了解我是否有图像或文本,以及是否有图像,之后是否有文本。
我不习惯使用枚举和范围参数;这些文档并没有真正帮助我理解如何使其工作。
你是如何做到这一点的?
我现在唯一的代码是来自另一篇文章,如果只有一张图片的话,那是很有帮助的。
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;
}
}];发布于 2015-06-18 12:48:24
这样做的目的是保持相同的逻辑,但是使用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");https://stackoverflow.com/questions/30912075
复制相似问题