[英]Xcode Objective-C | iOS: delay function / NSTimer help?
所以我正在開發我的第一個iOS應用程序,我需要幫助。
現在有一個簡單的程序,我大約有9個按鈕,當我按下第一個按鈕或任何一個按鈕時,我只希望第一個按鈕突出顯示60毫秒,取消突出顯示,第二個按鈕突出顯示,等待60毫秒,取消突出顯示等等。其余的按鈕,看起來就像是正在移動的LED。
我看過嘗試過的睡眠/非睡眠狀態,但是一旦完成睡眠時間,似乎就一起跳過了突出顯示/取消突出顯示的位置。
例如:
- (void) button_circleBusy:(id)sender{
firstButton.enabled = NO;
sleep(1);
firstButton.enabled = YES;
其余的按鈕等等。 它會延遲,但不會延遲“ firstButton.enabled = NO;”。 我有每個按鈕的“禁用狀態”的圖片,但我從未看到過。
任何幫助表示贊賞! 我研究了NSTimer,但是不確定如何實現它。
謝謝。
保羅
sleep
不起作用,因為只能在您的主線程返回系統后才更新顯示。 NSTimer是必經之路。 為此,您需要實現計時器將調用的方法以更改按鈕。 一個例子:
- (void)button_circleBusy:(id)sender {
firstButton.enabled = NO;
// 60 milliseconds is .06 seconds
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
}
- (void)goToSecondButton:(id)sender {
firstButton.enabled = YES;
secondButton.enabled = NO;
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToThirdButton:) userInfo:nil repeats:NO];
}
...
int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
do something to the button(s)
});
更少的代碼就是更好的代碼。
[NSThread sleepForTimeInterval:0.06];
迅速:
Thread.sleep(forTimeInterval: 0.06)
嘗試
NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
[NSThread sleepUntilDate:future];
我想補充一點Avner Barr的答案。 當使用int64時,當我們超過1.0值時,該函數的延遲似乎有所不同。 所以我認為在這一點上,我們應該使用NSTimeInterval。
因此,最終代碼是:
NSTimeInterval delayInSeconds = 0.05; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ //do your tasks here });
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
是最好的一種。 使用睡眠(15); 將導致用戶無法執行任何其他操作。 使用以下功能,您可以將goToSecondButton替換為適當的選擇器或命令,這些選擇器或命令也可以來自框架。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.