2014-02-06 2 views
-1

Как установить различный цвет чисел и слов, присутствующих в NSString, динамически.Как установить различный цвет для чисел, присутствующих в NSString динамически

Мне это нужно без использования других классов. Есть ли простой способ сделать это с помощью NSAttributedString. Мне это нужно для UILabel.

Например: мяч, летучей мыши, пни, перчатки, ... п. и т. д. *

Я хочу, чтобы подсчеты одного цвета и названия элементов в другом цвете. Любая помощь приветствуется.

+2

Что вы попробовали? –

ответ

2

Вы можете использовать NSRegularExpression, чтобы найти номера в тексте и после этого просто добавьте атрибут к строке атрибута:

NSString *testString = @"1 ball, 1 bat, 3 stumps, 4 Gloves"; 
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:testString]; 

    NSRange searchedRange = NSMakeRange(0, [testString length]); 
    NSString *pattern = @"\\d+"; 
    NSError *error = nil; 

    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error]; 

    NSArray* matches = [regex matchesInString:testString options:0 range: searchedRange]; 
    for (NSTextCheckingResult* match in matches) 
    { 
     NSString* matchText = [testString substringWithRange:[match range]]; 
     [attStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:[match range]]; 
     NSLog(@"Match: %@", matchText); 
    } 
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)]; 
    lab.attributedText = attStr; 
    [self.view addSubview:lab]; 
+0

Спасибо, Грег, что спасает мой день :) – arunit21

1

Использование NSAttributedString на самом деле использует другой класс :) Однако я советую вам подготовить его с помощью NSMutableAttributedString, а затем сохранить версию без изменений, поскольку ее легко читать. Во всяком случае некоторые непроверенный код должен выглядеть следующим образом:

NSMutableAttributedString* message = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"1 word 2 word"] attributes:nil]; 
[message addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, 1)]; 
[message addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(8, 1)]; 

Также вы можете сразу добавить NSAttributedString 's с заданными свойствами, а не устанавливать их с диапазоном:

NSMutableAttributedString* message = [[NSMutableAttributedString alloc] init]; 
//set text 
[message appendAttributedString:[[NSAttributedString alloc] initWithString:@"1" attributes:@{ 
                          NSFontAttributeName : [UIColor greenColor] 
                          }]]; 
[message appendAttributedString:[[NSAttributedString alloc] initWithString:@" word"]]; 

[message appendAttributedString:[[NSAttributedString alloc] initWithString:@"2" attributes:@{ 
                          NSFontAttributeName : [UIColor redColor] 
                          }]]; 
[message appendAttributedString:[[NSAttributedString alloc] initWithString:@" word"]]; 
Смежные вопросы