2014-07-03 17 views
0

我尝试下面的代码:如何以时间间隔字母更改标签文字颜色?

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myTimerMethod:) userInfo:nil repeats:NO]; 

-(void)myTimerMethod:(NSTimer*)timer 
{ 

    label.textColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.22 alpha:1.0]; 

} 

,但我希望像下面的图像类型而改变颜色。

enter image description here

+0

你的问题还不清楚。你发布的代码发生了什么,你究竟想要什么? – rdelmar

回答

2

的UILabel现在支持属性串。所以你可以做类似以下的事情

int lengthOfTextToColor = 0; 
NSMutableAttributedString *textString = [[NSMutableAttributedString alloc] initWithString:@"I think you are making a karaoke app"]; 

-(void)colorChangeTimer:(NSTimer *)timer { 
    lengthOfTextToColor ++; 
    NSRange range = NSMakeRange(0, lengthOfTextToColor); 
    NSDictionary *colorAttribute = @{NSForegroundColorAttributeName:[UIColor blueColor]}; 
    [textString setAttributes: colorAttribute range:range]; 
    self.label.attributedText = textString; 
} 

但是归因字符串有其局限性。 如果你正在寻找实现真正花哨的文本,拉起你的袜子,并检查Text Programming Guide和CoreText框架。你可以找到很多tutorials for Core Text

+0

谢谢你对我的工作......但是,如果(lengthOfTextToColor == [textString length]){ [timer invalidate]; return; } – RameshIos

0

你必须使用NSMutableAttributedString

_string = [[NSMutableAttributedString alloc] initWithString:@"your string"]; 
_index = 0; 
[NSTimer scheduledTimerWithInterval:1.0 target:self selector:@selector(yourSelector) userInfo:nil repeats:NO]; 

- (void)yourSelector { 
    [_string setAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:0 green:0 blue:0 alpha:1]} range:NSMakeRange(_index, 1)]; 
    [label setAttributedText:_string]; 
    _index++; 
} 
相关问题