如何在NSString中获取特定字符的所有NSRange? [英] How to get all NSRange of a particular character in a NSString?

查看:784
本文介绍了如何在NSString中获取特定字符的所有NSRange?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个NSStrings: orgText searchLetter

我想突出显示每一个使用红色在 orgText 中出现searchLetter。

如何获得 NSRange 所有出现的 searchLetter

例如:

I have two NSStrings: orgText and searchLetter.
I want to highlight every occurrences of the searchLetter in the orgText with a red color.
How can I get the NSRange of all occurrences of the searchLetter ?
for eg :

suppose: orgText = "abcahaiapaoiuiapplma"
         searchLetter = "a".

我想用红色突出显示abcahaiapaoiuiapplma中的所有a事件。

谢谢。

I want to hightlight all "a" occurrences in "abcahaiapaoiuiapplma" with red color.
Thanks.

推荐答案

我为我的项目写了这个方法 - 带高亮的SUITextView

I wrote this method for my project - SUITextView with highlight:

- (NSMutableAttributedString*) setColor:(UIColor*)color word:(NSString*)word inText:(NSMutableAttributedString*)mutableAttributedString {

    NSUInteger count = 0, length = [mutableAttributedString length];
    NSRange range = NSMakeRange(0, length);

    while(range.location != NSNotFound)
    {
        range = [[mutableAttributedString string] rangeOfString:word options:0 range:range];
        if(range.location != NSNotFound) {
            [mutableAttributedString setTextColor:color range:NSMakeRange(range.location, [word length])];
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            count++; 
        }
    }

    return mutableAttributedString;
}

在我的NSMutableAttributedString类别中:

And in my category of NSMutableAttributedString:

- (void) setTextColor:(UIColor*)color range:(NSRange)range {
    // kCTForegroundColorAttributeName
    [self removeAttribute:(NSString*)kCTForegroundColorAttributeName range:range]; // Work around for Apple leak
    [self addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)color.CGColor range:range];
}

这篇关于如何在NSString中获取特定字符的所有NSRange?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆