[英]objective-c: Animate button before timer ends
我正在研究一款非常簡單的iPhone游戲,它涉及根據隨機語音提示連續多次選擇正確的彩色按鈕。 我設置它,如果按鈕是一種顏色並被點擊,它每次都會變為硬編碼顏色(例如,如果你點擊紅色,它總是變成藍色)。 顏色變化方法在IBOutlet中設置。 我在while循環中設置了一個計時器,當計時器結束時,它檢查玩家是否做出了正確的選擇。 問題是在計時器用完之后才會發生按鈕顏色更改,這會導致用於檢查正確答案的方法出現問題。 有沒有辦法讓這種顏色變化立即發生? 從我搜索到的內容來看,我知道它與故事板動作有關,直到代碼執行之后才會發生,但我沒有發現使用計時器的任何事情。 以下是在答案正確時調用計時器的方法的一部分:
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];
}
突出的兩件事之一
NSTimer
異步運行 - 這是理想的選擇。 因此,讓我們來了解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;
}
現在
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.