Split NSAttributedString into Image + NSString
I have NSAttributedString
one which can contain 3 different things:
- Just a picture. (Appendix)
- Text only
- An image followed by text (/! \ Not the other way around, never).
I am trying to "scan" this object to see if I have an image or text, and if there is an image, if there is text after that.
I am not comfortable using enumeration and range parameters; the documentation didn't really help me figure out how to do this.
How would you achieve this?
- Extract image if any
- Extract the string, if any (either separately or after the image).
The only code I have right now is another SO post that was helpful if there was only an image.
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;
}
}];
source to share
The idea is to keep the same logic but using NSMutableAttributedString
instead NSAttributedString
, save the NSRange
image and delete it.
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");
source to share