簡體   English   中英

禁用計時器iOS上的按鈕

[英]Disable a button on a timer iOS

我正在使用Objective-C在XCode 7上創建一個計時器應用,並且我想在執行以下代碼時禁用連接到動作startCount的按鈕

- (IBAction)startCount:(id)sender {

countInt = 0;
self.Label.text = [NSString stringWithFormat:@"%i", countInt];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countTimer) userInfo:nil repeats:YES];
}

我需要添加以下哪行代碼來禁用連接到操作startCount的按鈕?

謝謝

您需要通過enabled標志disable發送者:

((UIButton*)sender).enabled = false;

別忘了在計時器結束后重新啟用按鈕。

如果啟用狀態為“否”,則控件將忽略觸摸事件[...]

除了上述代碼中進行的UIButton* ,還可以:更改方法簽名以使用UIButton* ,而不僅僅是ID,這樣可以確保強制轉換不會失敗。 強制轉換的微小變化將改為UIControl*轉換為UIControl*

如果我正確理解您的意見:為了使您的代碼更易於理解(並避免在有多個按鈕可能被輕按/禁用的情況下避免令人不快的競爭情況),我建議您避免使用計時器。 相反,考慮這樣的dispatch_after()

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    sender.userInteractionEnabled = false;
});

我們將sender傳遞到方法中,這將是被點擊的按鈕。 1 * NSEC_PER_SEC表示“延遲一秒鍾”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM