富文本中计算多个占位符的range,然后替换成对应图片
用 ^^^^ 占位,然后逆序替换成对应的图片
NSString *note;
NSArray *imageArr;
if (_page_type == Outdoor_Guide_Page_Type_1) {
note = LOCALSTRING(@"1. Select a speaker as outdoor master speaker.\n2. Long press “^^^^” button to enter outdoor master mode.");
imageArr = @[@"OutdoorGuide_btn_001"];
} else {
note = LOCALSTRING(@"Long press “^^^^” button and “^^^^” on your expected speakers that would connected to outdoor master speaker.");
imageArr = @[@"OutdoorGuide_btn_001",@"OutdoorGuide_btn_002"];
}
[self setupNoteLabel:note imageArray:imageArr];
- (void)setupNoteLabel:(NSString *)note imageArray:(NSArray *)imageArr {
NSMutableArray *imgStrArr = [NSMutableArray array];
for (int i = 0; i < imageArr.count; i++) {
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:imageArr[i]];
NSAttributedString *imgStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
[imgStrArr addObject:imgStr];
}
NSMutableParagraphStyle *pStyle = [[NSMutableParagraphStyle alloc]init];
pStyle.lineSpacing = 8;
NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:note];
[noteStr addAttributes:@{NSForegroundColorAttributeName: THEME_LIGHT_COLOR,
NSFontAttributeName: [UIFont systemFontOfSize:14],
NSParagraphStyleAttributeName:pStyle}
range:NSMakeRange(0, noteStr.length)];
// 正则匹配 占位符
NSString *regexStr = @"(\\^\\^\\^\\^)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:nil];
NSArray *matches = [regex matchesInString:note options:0 range:NSMakeRange(0, note.length)];
NSMutableArray *rangeArr = [NSMutableArray array];
// 倒序获取 占位符ranges (防止正序替换的时候,由于图片replace后造成的整体location错误)
[matches enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSTextCheckingResult *result, NSUInteger idx, BOOL * _Nonnull stop) {
NSRange range = result.range;
[rangeArr addObject:[NSValue valueWithRange:range]];
}];
// 替换
for (int i = 0; i < rangeArr.count; i++) {
NSValue *value = rangeArr[i];
NSRange range = value.rangeValue;
[noteStr replaceCharactersInRange:range withAttributedString:imgStrArr[rangeArr.count - 1 - i]];
}
_noteLabel.attributedText = noteStr;
}
阅读量
loading...