实现搜索字符与搜索内容突出显示

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;
                    }
                }

转载于:https://www.cnblogs.com/coderTan/p/6377492.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值