在字符串中获取多个动态字符串范围

时间:2016-02-04 08:25:14

标签: ios range substring

我一直在尝试在字符串中获取多个字符串范围。 要更改这些字符串的颜色。

更改文字颜色我使用 UILabel + FormattedText.h 类别。

例如在字符串中: - @“@ hello @test testing #label”

我希望这些子串以红色显示,并用@或#。

盯着

现在输出@hello @test #label将为红色,测试将为正常颜色。

任何帮助?

2 个答案:

答案 0 :(得分:1)

你可以通过这样的方式实现它。最后,“rangesArray”将包含以“@”和“#”作为前缀的字符串范围,“attrString”将是将这些字符串转换为红色文本的属性字符串。

    NSString * test = @"@hello @test testing #label";

    NSArray *array = [test componentsSeparatedByString:@" "];
    NSMutableArray *rangesArray = [NSMutableArray array];

    NSInteger prevStringLength = 0;
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:test];

    for (NSString *str in array) {
        if ([str hasPrefix:@"@"] || [str hasPrefix:@"#"]) {
            [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(prevStringLength, str.length)];
            [rangesArray addObject:[NSValue valueWithRange:NSMakeRange(prevStringLength, str.length)]];
        }

        prevStringLength += (str.length + 1);
    }

答案 1 :(得分:0)

使用以下方法完成它

+(void) setTextColor:(NSString *)stringToScan Label:(UILabel *)label CharacterToCheck:(NSString *)characterToCheck Color:(UIColor *)color
{
    NSMutableArray *substrings = [NSMutableArray new];
    NSScanner *scanner = [NSScanner scannerWithString:stringToScan];
    [scanner scanUpToString:characterToCheck intoString:nil]; // Scan all characters before CharacterToCheck
    while(![scanner isAtEnd]) 
    {
        NSString *substring = nil;
        [scanner scanString:characterToCheck intoString:nil]; // Scan the # character
        if([scanner scanUpToString:@" " intoString:&substring])
        {
            // If the space immediately followed the CharacterToCheck, this will be skipped
            if([substring rangeOfString:characterToCheck].location == NSNotFound)
            {
                substring = [NSString stringWithFormat:@"%@%@",characterToCheck,substring];
            }

        [substrings addObject:substring];
        }
        [scanner scanUpToString:characterToCheck intoString:nil]; // Scan all characters before next CharacterToCheck
    }



    for(int i=0;i<[substrings count];i++)
    {
        NSString *str = [substrings objectAtIndex:i];

        NSRange range = [stringToScan rangeOfString:str];
        if(range.location != NSNotFound)
        {
            [label setTextColor:color range:NSMakeRange(range.location, range.length)];
        }
    }
}