iOS 字符串前后插入图片,指定字符后插入图片

### 一、字符串前(后)插入图片 ![标题头插入图片.jpg](https://upload-images.jianshu.io/upload_images/2887690-7aafe9f9d386ae8c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/880) ``` // 利用 `NSTextAttachment` 生成图片再转化为可变字符串 NSTextAttachment *attch = [[NSTextAttachment alloc] init]; attch.image = [UIImage imageNamed:@"allresponse_title"]; attch.bounds = CGRectMake(0, 0, attch.image.size.width, attch.image.size.height); NSMutableAttributedString *result = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@",channelModel.title]]; NSAttributedString *b_string = [NSAttributedString attributedStringWithAttachment:attch]; [result insertAttributedString:b_string atIndex:0]; self.titleLabel.attributedText = result; ``` ### 二、关键字命中字符串显示高亮并插入图片 ![指定字符后插入图片.png](https://upload-images.jianshu.io/upload_images/2887690-8c092ba0a8744f63.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800) ``` // 关键词高亮显示 - (void)setHighLightWordWithModel:(WEShareholderModel *)model { // 插入多个关键字 if ([self.correlationCompanyArr isKindOfClass:[NSArray class]] && self.correlationCompanyArr.count > 0) { NSMutableArray *tempArray = [[NSMutableArray alloc] init]; NSMutableArray *highWordArray = [[NSMutableArray alloc] init]; // 1. 寻找关键词位置 for (WECompanyModel *mm in self.correlationCompanyArr) { NSString *highword = mm.name; if ([mm.keywords isKindOfClass:[NSString class]] && [mm.keywords isNoEmpty]) { highword = mm.keywords; } [highWordArray addObject:highword]; if ([highword isKindOfClass:[NSString class]] && [model.content containsString:highword]) { NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:model.content]; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:highword options:0 error:nil]; NSArray *matches = [regex matchesInString:model.content options:0 range:NSMakeRange(0, model.content.length)]; // 只显示一次 if ([matches isKindOfClass:[NSArray class]] && matches.count > 0) { matches = [matches subarrayWithRange:NSMakeRange(0, 1)]; } for(NSTextCheckingResult *result in [matches objectEnumerator]){ NSRange matchRange = [result range]; [tempArray addObject:[NSValue valueWithRange:matchRange]]; } } } if (tempArray.count == 0) { // 无匹配企业 NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:model.content]; [attrText addAttribute:NSFontAttributeName value:kFontPingFangRegular(19) range:NSMakeRange(0, attrText.string.length)]; if (self.keyword) { // 有关键词,匹配关键词高亮 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:self.keyword options:0 error:nil]; NSArray *matches = [regex matchesInString:model.content options:0 range:NSMakeRange(0, model.content.length)]; for(NSTextCheckingResult *result in [matches objectEnumerator]){ NSRange matchRange = [result range]; [attrText setColor:kAssistNewColor range:matchRange]; } } self.detailLabel.attributedText = attrText; } else { // 2.根据关键词位置,插入图片 int i = 0; NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:model.content]; [title addAttribute:NSFontAttributeName value:kFontPingFangRegular(19) range:NSMakeRange(0, title.string.length)]; NSArray *sortArray = [tempArray sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { if ([obj1 isKindOfClass:[NSValue class]] && [obj2 isKindOfClass:[NSValue class]]) { NSValue *value1 = obj1; NSValue *value2 = obj2; NSRange range1 = [value1 rangeValue]; NSRange range2 = [value2 rangeValue]; return (range1.location < range2.location ? NSOrderedDescending : NSOrderedAscending); } return NSOrderedAscending; }]; // 2.1从后往前插入,就不会影响前面获取的位置坐标 for (NSValue *value in sortArray) { NSRange range = [value rangeValue]; NSTextAttachment *attachment = [[NSTextAttachment alloc] init]; attachment.image = [UIImage imageNamed:@"icon-company"]; attachment.bounds = CGRectMake(2, 0, 17.5, 15); NSAttributedString *imageAttachment = [NSAttributedString attachmentStringWithContent:attachment.image contentMode:UIViewContentModeScaleAspectFit attachmentSize:attachment.bounds.size alignToFont:title.font alignment:YYTextVerticalAlignmentTop]; [title insertAttributedString:imageAttachment atIndex:range.location+range.length]; i++; } // 3.全部完成后,给关键词高亮,添加点击事件 (如果在之前设置高亮,位置会偏移) for (WECompanyModel *mm in self.correlationCompanyArr) { NSString *highword = mm.name; if ([mm.keywords isKindOfClass:[NSString class]] && [mm.keywords isNoEmpty]) { highword = mm.keywords; } if ([highword isKindOfClass:[NSString class]] && [title.string containsString:highword]) { NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:highword options:0 error:nil]; NSArray *matches = [regex matchesInString:title.string options:0 range:NSMakeRange(0, title.string.length)]; if ([matches isKindOfClass:[NSArray class]] && matches.count > 0) { matches = [matches subarrayWithRange:NSMakeRange(0, 1)]; } for(NSTextCheckingResult *result in [matches objectEnumerator]){ NSRange matchRange = [result range]; [title setTextHighlightRange:matchRange color:kAssistSubColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) { [self companyBtnOnClickWithModel:mm]; }]; } } if (self.keyword) { // 有关键词,匹配关键词高亮 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:self.keyword options:0 error:nil]; NSArray *matches = [regex matchesInString:title.string options:0 range:NSMakeRange(0, title.string.length)]; for(NSTextCheckingResult *result in [matches objectEnumerator]){ NSRange matchRange = [result range]; [title setColor:kAssistNewColor range:matchRange]; } } } self.detailLabel.attributedText = title; } } else { NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:model.content]; [attrText addAttribute:NSFontAttributeName value:kFontPingFangRegular(19) range:NSMakeRange(0, attrText.string.length)]; if (self.keyword) { // 有关键词,匹配关键词高亮 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:self.keyword options:0 error:nil]; NSArray *matches = [regex matchesInString:model.content options:0 range:NSMakeRange(0, model.content.length)]; for(NSTextCheckingResult *result in [matches objectEnumerator]){ NSRange matchRange = [result range]; [attrText setColor:kAssistNewColor range:matchRange]; } } self.detailLabel.attributedText = attrText; } } ```

你可能感兴趣的:(iOS 字符串前后插入图片,指定字符后插入图片)