我知道这样的事情已经被问到了,但我找不到解决问题的方法。
所以,我有一个NSString,有时在文本中包含一个图像名称,如:
Lorem ipsum....
image.png
... dolor sit elit lamet
我想在我的NSMutableAttributedString中为该空间添加名为'image.png'的图像。
这是我获取匹配的代码
NSString *regEx = @"([a-z])+(?:([0-9])+){0,1}.png";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:regEx
options:NSRegularExpressionCaseInsensitive error:&error];
if(error != nil){
NSLog(@"Error: %@",error);
} else{
[regex enumerateMatchesInString:myString options:0 range:NSMakeRange(0, [myString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
// your code to handle matches here
NSLog(@"found!");
}];
}
如何在NSMutableAttributedString中添加图像,为每个找到的子字符串调用imageNamed
函数?
答案 0 :(得分:0)
显然我已经解决了。在for里面有代码用NSMutableAttributedString
中的图像替换子字符串。此外,我决定在类似(但不同)的问题中将一个反向的for
灵感放在先前的答案中
NSMutableAttributedString *formattedText = myString.mutableAttributedString;
// Look for image
NSString *regEx = @"([a-z])+(?:([0-9])+){0,1}.png";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:regEx
options:NSRegularExpressionCaseInsensitive error:&error];
if(error != nil){
NSLog(@"Error: %@",error);
} else{
NSArray *matches = [regex matchesInString:myString
options:kNilOptions
range:NSMakeRange(0, myString.length)];
for (NSTextCheckingResult *result in [matches reverseObjectEnumerator])
{
NSString *insideString = [myString substringWithRange:[result rangeAtIndex:0]];
UIImage *image = [UIImage imageNamed:insideString];
NSTextAttachment *imageAttachment = [NSTextAttachment new];
imageAttachment.image = image;
NSAttributedString *replacementForTemplate = [NSAttributedString attributedStringWithAttachment:imageAttachment];
[formattedText replaceCharactersInRange:result.range
withAttributedString:replacementForTemplate];
NSLog(@"found! -> %@", insideString);
}
}
相反,mutableAttributedString
属性属于NSString类别。这是它的代码
- (NSMutableAttributedString *)mutableAttributedString {
return [[NSMutableAttributedString alloc] initWithString:self];
}