首页 > 代码库 > 实现搜索字符与搜索内容突出显示
实现搜索字符与搜索内容突出显示
1.创建可显示的字符集。
@property (nonatomic, copy) NSString *filter;
@property (nonatomic, strong) NSAttributedString *merchantShopNameRich;
2.获取到具体的搜索字符。
- (NSAttributedString *)merchantShopNameRich {
if (!_merchantShopNameRich) {
_merchantShopNameRich = [self stringColor:self.merchantShopName fontSize:15 searchText:self.filter];
}
return _merchantShopNameRich;
}
3.将确认的搜索字符与搜索结果进行匹配处理。
- (NSAttributedString *)stringColor:(NSString *)string fontSize:(NSInteger)fontSize searchText:(NSString *)fiter{
//以不区分大小写的方式呈现文字
UIColor * color = [UIColor colorTextAssistColor];
NSMutableAttributedString * richStr = [[NSMutableAttributedString alloc]initWithString:string?:@""];
NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:color};
if (fiter.length <= 0) {
return nil;
}
if ([string rangeOfString:fiter options:NSCaseInsensitiveSearch].location != NSNotFound) {
NSRange range = [string rangeOfString:fiter options:NSCaseInsensitiveSearch];
[richStr addAttributes:dic range:range];
}
return richStr;
}
4.在cell或控件内部对字符集进行具体的赋值。
- (void)setModel:(SearchModel *)model {
_model = model;
SearchCellFrame *cellFrameModel = [[SearchCellFrame alloc] initWithContent:model];
_collectionView.frame = cellFrameModel.collecttionFrame;
[_headeImage sd_setImageWithURL:[NSURL URLWithString:model.storefrontimagePath] placeholderImage:IMG(@"load_Price")];
// 店铺详情
_storeName.attributedText = model.merchantShopNameRich;
_signatureLab.text = model.signature;
_totalLabel.text = [NSString stringWithFormat:@"已售:%ld", model.orderCountNum];
_distanceLabel.text = model.distanceKM;
if (model.isShopTime == 0) {
_isSalesLab.hidden = NO;
}else {
_isSalesLab.hidden = YES;
}
[self.collectionView reloadData];
}
5.在控制器中,返回的结果赋值给filter字符串。
for (SearchModel * model in arrays) {
model.filter = weakSelf.saerchName;
for (FoodDetailModel *item in model.Commodity) {
item.goodsFilter = weakSelf.saerchName;
}
}
实现搜索字符与搜索内容突出显示