gpt4 book ai didi

ios - 尝试使用 NSTimer 为 UILabel 提供脉冲效果,但计时器始终相互冲突

转载 作者:行者123 更新时间:2023-11-29 03:17:48 26 4
gpt4 key购买 nike

为了显示某个状态正在进行中,我正在“脉冲”对应于该状态的 UILabel,反复将其从白色渐变为深灰色。

我正在使用 NSTimers 完成此操作,如下所示:

- (void)pulseColorsOfLabel:(NSTimer *)timer {
_timer = timer;
UILabel *labelToPulse = timer.userInfo;

// Check pulseCycle to determine at what point in the color transition the label is
if (_pulseCycle == 0) {
[UIView transitionWithView:labelToPulse duration:0.75 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
labelToPulse.textColor = [UIColor darkGrayColor];
} completion:nil];

_pulseCycle = 1;
}
else if (_pulseCycle == 1) {
[UIView transitionWithView:labelToPulse duration:0.75 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
labelToPulse.textColor = [UIColor whiteColor];
} completion:nil];

_pulseCycle = 0;
}
}

然后我使用 NSTimer 调用使该方法每 0.75 秒触发一次:

[NSTimer scheduledTimerWithTimeInterval:0.75 target:self selector:@selector(pulseColorsOfLabel:) userInfo:self.stateLabel repeats:YES];

随着应用程序经历各种状态,它将刚刚完成的状态标签标记为绿色,使计时器无效,然后使用另一个 NSTimer 将下一个状态标签更改为脉冲(应用程序必须经历多个状态)称呼。基本上,当状态发生变化时,一个方法作为委托(delegate)被调用,然后使用 switch 语句检查状态,并设置适当的颜色和脉冲。

问题是,有时在所有状态标签变绿的过程中,有些会完全消失(因为我假设它们卡在白色背景下的褪色到白色状态),有时它们会保持黑色,有时它们会跳动非常零星。

我知道这是计时器的问题,就好像我没那么花哨,只是让它在进行时将状态标签更改为橙色而不是脉冲,它每次都工作得很好。

我可以在这里做什么以确保所有计时器调用相互配合工作良好,并且不会弄乱标签的颜色?有什么想法吗?

最佳答案

我注意到在您的代码中 _timer 是在计时器触发时分配的,这意味着如果当前计时器还没有至少触发一次,您将无法取消它。尝试在安排时使计时器无效并分配它:

[_timer invalidate];
_timer = [NSTimer scheduledTimerWithTimeInterval:0.75 target:self selector:@selector(pulseColorsOfLabel:) userInfo:self.stateLabel repeats:YES];

如果这不起作用,您的某些动画可能会被打断。在添加新动画之前尝试删除旧动画:

UILabel *labelToPulse = timer.userInfo;
[labelToPulse.layer removeAllAnimations];

关于ios - 尝试使用 NSTimer 为 UILabel 提供脉冲效果,但计时器始终相互冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21468573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com