gpt4 book ai didi

iphone - objective-c:在计时器结束前动画按钮

转载 作者:行者123 更新时间:2023-11-28 22:58:49 26 4
gpt4 key购买 nike

我正在开发一款非常简单的 iPhone 游戏,该游戏涉及根据随机语音提示连续多次选择正确的彩色按钮。我设置了它,这样如果按钮是一种颜色并被点击,它每次都会变成硬编码的颜色(例如,如果你点击红色,它总是变成蓝色)。颜色更改方法在 IBOutlet 中设置。我在 while 循环中设置了一个计时器,当计时器结束时,它会检查玩家是否做出了正确的选择。问题是直到计时器用完后按钮颜色才会发生变化,这会导致用于检查正确答案的方法出现问题。有没有办法让这种颜色变化立即发生?根据我的搜索,我知道它与直到代码执行后才发生的 Storyboard Action 有关,但我没有发现任何与使用计时器有关的事情。如果答案正确,下面是调用计时器的方法的一部分:

BOOL rightChoice = true;
int colorNum;
NSDate *startTime;
NSTimeInterval elapsed;
colorNum = [self randomizeNum:middle];
[self setTextLabel:colorNum];
while (rightChoice){
elapsed = 0.0;
startTime = [NSDate date];
while (elapsed < 2.0){
elapsed = [startTime timeIntervalSinceNow] * -1.0;
NSLog(@"elapsed time%f", elapsed);
}
rightChoice = [self correctChoice:middleStatus :colorNum];
colorNum = [self randomizeNum:middle];
}

最佳答案

两件事中的一件脱颖而出

  • 您正在使用 while 循环作为计时器,不要这样做 - 该操作是同步的。
  • 如果这是在主线程上运行,并且您的代码没有返回,您的 UI 将会更新。口头禅是:“当你不返回时,你就是在阻塞。”
  • Cocoa 有异步运行的 NSTimer - 它在这里很理想。

所以让我们get to grips with NSTimer (或者,您可以使用 GCD 并将队列保存到 ivar,但 NSTimer 似乎是正确的方法)。

创建一个名为 timer_ 的 ivar:

// Top of the .m file or in the .h
@interface ViewController () {
NSTimer *timer_;
}
@end

制作一些启动和停止功能。如何称呼这些取决于您。

- (void)startTimer {
// If there's an existing timer, let's cancel it
if (timer_)
[timer_ invalidate];

// Start the timer
timer_ = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(onTimerFinish:)
userInfo:nil
repeats:NO];
}

- (void)onTimerFinish:(id)sender {
NSLog(@"Timer finished!");

// Clean up the timer
[timer_ invalidate];
timer_ = nil;
}

- (void)stopTimer {
if (!timer_)
return;

// Clean up the timer
[timer_ invalidate];
timer_ = nil;
}

现在

  • 将您的计时器测试代码放入 onTimerFinish 函数中。
  • 创建一个存储当前选择的 ivar。做出选择时更新此 ivar,并对 UI 进行相关更改。如果满足停止条件,则调用 stopTimer。
  • 在 onTimerFinished 中,如果需要,您可以有条件地再次调用和 startTimer。

希望这对您有所帮助!

关于iphone - objective-c:在计时器结束前动画按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10334508/

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