我想为我的标签使用一点动画。 如果我尝试从IBAction按钮或ViewDidLoad调用此动画,并且一切正常。
- (void)animateLabelShowText:(NSString*)newText characterDelay:(NSTimeInterval)delay
{
[self.myLabel setText:@""];
for (int i=0; i<newText.length; i++)
{
dispatch_async(dispatch_get_main_queue(),
^{
[self.myLabel setText:[NSString stringWithFormat:@"%@%C", self.myLabel.text, [newText characterAtIndex:i]]];
});
[NSThread sleepForTimeInterval:delay];
}
}
呼叫:
-(void) doStuff
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
^{
[self animateLabelShowText:@"Hello Vignesh Kumar!" characterDelay:0.5];
});
}
但是如果我把这个方法放在一个协议中,我试着从例如一个委托中调用它,什么都没有出现。可能我在GDC(Grand Central Dispatch)逻辑中遗漏了一些东西:
...
if ([_myDelegate respondsToSelector:@selector(doStuff:)])
{
NSLog(@" Yes I'm in and try to execute doStuff..");
[_myDelegate doStuff]; // NOTHING TO DO
}
...
当我使用类似函数更改函数doStuff时发生了同样的情况:
-(void)typingLabel:(NSTimer*)theTimer
{
NSString *theString = [theTimer.userInfo objectForKey:@"string"];
int currentCount = [[theTimer.userInfo objectForKey:@"currentCount"] intValue];
currentCount ++;
NSLog(@"%@", [theString substringToIndex:currentCount]);
[theTimer.userInfo setObject:[NSNumber numberWithInt:currentCount] forKey:@"currentCount"];
if (currentCount > theString.length-1) {
[theTimer invalidate];
}
[self.myLabel setText:[theString substringToIndex:currentCount]];
}
通过
调用-(void) doStuff
{
NSString *string =@"Risa Kasumi & Yuma Asami";
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:string forKey:@"string"];
[dict setObject:@0 forKey:@"currentCount"];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(typingLabel:) userInfo:dict repeats:YES];
[timer fire];
}
答案 0 :(得分:0)
我已在我的委托文件.m
中使用NSNotificationCenter解决了问题 viewDidLoad: 中的
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(makeEffectOnMyLabel:) name:@"lblUpdate" object:nil];
我的协议功能>>
dispatch_async( dispatch_get_main_queue(),
^{
...I've populated a dictionary userInfo with my vars
[[NSNotificationCenter defaultCenter] postNotificationName:@"lblUpdate" object:nil userInfo:userInfo];
});
在为准备打字标签创建的函数
-(void) makeEffectOnMyLabel:(NSNotification *) notification
{
..changes between dictionaries to prepare typingLabel..
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSDictionary* userInfo = [notification userInfo];
[dict setObject:[userInfo objectForKey:@"myRes"] forKey:@"myRes"];
[dict setObject:[userInfo objectForKey:@"myType"] forKey:@"myType"];
[dict setObject:[userInfo objectForKey:@"frase"] forKey:@"frase"];
[dict setObject:@0 forKey:@"currentCount"];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(typingLabel:) userInfo:dict repeats:YES];
[timer fire];
}
现在一切正常。