iOS替换指定文字为图片
2020-04-14 本文已影响0人
最强的小强
example:"i说i想精品课",替换其中的字母‘i’为图片。
效果如下:
图文混排.png
- 具体步骤:
一、导入#import <YYKit.h>
利用CocoaPods 'pod 'YYKit''
二、寻找指定文字的位置
// 查找子字符串在父字符串的所有位置
- (NSMutableArray *)getRangeStr:(NSString *)text findText:(NSString *)findText {
NSMutableArray *arrayRanges = [NSMutableArray arrayWithCapacity:20];
if (findText == nil && [findText isEqualToString:@""]) {
return nil;
}
NSRange rang = [text rangeOfString:findText]; //获取第一次出现的range
if (rang.location != NSNotFound && rang.length != 0) {
[arrayRanges addObject:[NSNumber numberWithInteger:rang.location]];//将第一次的加入到数组中
NSRange rang1 = {0,0};
NSInteger location = 0;
NSInteger length = 0;
for (int i = 0;; i++) {
if (0 == i) {//去掉这个xxx
location = rang.location + rang.length;
length = text.length - rang.location - rang.length;
rang1 = NSMakeRange(location, length);
} else {
location = rang1.location + rang1.length;
length = text.length - rang1.location - rang1.length;
rang1 = NSMakeRange(location, length);
}
// 在一个range范围内查找另一个字符串的range
rang1 = [text rangeOfString:findText options:NSCaseInsensitiveSearch range:rang1];
if (rang1.location == NSNotFound && rang1.length == 0) {
break;
} else { //添加符合条件的location进数组
[arrayRanges addObject:[NSNumber numberWithInteger:rang1.location]];
}
}
return arrayRanges;
}
return nil;
}
三、替换文字为图片
if ([dataModel.title containsString:@"i"]) {
NSString *titleString = dataModel.title;
NSMutableAttributedString *alertAttributedString = [[NSMutableAttributedString alloc] initWithString:titleString];
// 图片
NSMutableArray *iArray = [self getRangeStr:dataModel.title findText:@"i"];
for (NSNumber *location in iArray) {
NSInteger subLocation = [location integerValue];
YYAnimatedImageView *insertImageView = [[YYAnimatedImageView alloc] initWithImage:[UIImage imageNamed:@"lesson_home_list_i"]];
insertImageView.frame = CGRectMake(0, 20, 7, 7*48/18);
NSMutableAttributedString *imageText= [NSMutableAttributedString attachmentStringWithContent:insertImageView contentMode:UIViewContentModeScaleAspectFit attachmentSize:CGSizeMake(14, 7*48/18) alignToFont:KBoldFont(20) alignment:YYTextVerticalAlignmentCenter]; // 图片转化为特殊字符
[alertAttributedString replaceCharactersInRange:NSMakeRange(subLocation, 1) withAttributedString:imageText];
}
[alertAttributedString addAttributes:@{NSFontAttributeName:KBoldFont(20),
NSForegroundColorAttributeName:[UIColor hexStringToColor:@"1c1c1c"]} range:NSMakeRange(0, alertAttributedString.length)];
self.titleLabel.attributedText = alertAttributedString;
} else {
self.titleLabel.text = dataModel.title;
}