iOS常用方法——字符串中含某个子字符串高亮效果的实现

我们在使用Google进行搜索时会看到搜索的关键字高亮的效果:
这里写图片描述
iOS客户端字符串中子字符串实现的代码:

+(NSMutableAttributedString *)stringWithHighLightSubstring:(NSString *)totalString substring:(NSString *)substring{
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:totalString];
    NSString * copyTotalString = totalString;
    NSMutableString * replaceString = [NSMutableString stringWithCapacity:0];
    for (int i = 0; i < substring.length; i ++) {
        [replaceString appendString:@" "];
    }
    while ([copyTotalString rangeOfString:substring].location != NSNotFound) {
        NSRange range = [copyTotalString rangeOfString:substring];
        //颜色如果统一的话可写在这里,如果颜色根据内容在改变,可把颜色作为参数,调用方法的时候传入
        [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:range];
        copyTotalString = [copyTotalString stringByReplacingCharactersInRange:range withString:replaceString];
    }
    return attributedString;
}

可以将该方法写在NSMutableAttributedString的分类中,用NSMutableAttributedString直接调用。
调用示例代码:

UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, self.view.frame.size.width - 40, 80)];
    label.attributedText = [NSMutableAttributedString stringWithHighLightSubstring:@"给岁月以文明,而不是给文明以岁月!" substring:@"文明"];
    [self.view addSubview:label];

效果展示:
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值