我有一个UITextView,并且我想使用NSTextAttachment替换一些特定的字符串为特定的图片。我可以将图像附件插入到UITextView中,并且我有一个方法,可以从文本视图的属性文本中返回一个NSString,该字符串将附件替换为特定的NSString:
-(NSString*)getStringFromAttributedString{
__block NSString *str = self.attributedText.string; // Trivial String representation
__block NSMutableString *string = [NSMutableString new]; // To store customized text
[self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop){
// enumerate through the attributes
NSString *v;
NSObject *x = [attributes valueForKey:@"NSAttachment"];
if(x){ // YES= This is an attachment
v = [Fuctions getObjectTag:x];
if(v == nil){
v=@"";
}
}else{
v = [str substringWithRange:range]; // NO=This is a text block.
}
// append value to string
[string appendString:v];
}];
return string;
}
现在我需要一个方法,它可以从
NSString
返回一个NSAttributedString
,并将某些字符串替换为图像附件,类似于这样,但我无法使其正常工作。-(NSMutableAttributedString*)getAttributedStringFromString:(NSString*)string{
// create NSMutableAttributedString from NSString in input
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
// create the attachment with image
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"myImageName.png"];
textAttachment.bounds = (CGRect) {0, -2, textAttachment.image.size};
// create NSMutableAttributedString with image attachment
NSMutableAttributedString *attrStringWithImage = [[NSAttributedString attributedStringWithAttachment:textAttachment] mutableCopy];
// here I'd like to replace all occurrences of a string (":D" this string for example) with my NSMutableAttributedString with image attachment).
return string;
}
我该如何做?
谢谢,希望我已经解释清楚了。
replaceCharactersInRange:withAttributedString:
方法。您可以使用NSRegularExpression
或其他“查找”方法在字符串示例中查找“:D”。 - Larme