我有一个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;
}
}];
最佳答案
想法是保持相同的逻辑,但是使用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");
关于ios - 将NSAttributedString拆分为Image + NSString,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30912075/