[英]Why is this UIButton still triggering event hander while disabled
我在視圖中有一個UIButton。 我像這樣附加一個事件處理程序:
[self.button addTarget:self
action:@selector(button_touchUpInside:)
forControlEvents:UIControlEventTouchUpInside];
處理程序如下所示:
-(void) button_touchUpInside:(id)sender
{
NSLog(@"%@", ((UIButton *)sender).enabled ? @"ENABLED" : @"DISABLED"); // Logs DISABLED
// Do stuff
}
我禁用了這樣的按鈕:
-(void)setEnabled:(BOOL)enabled
{
enabled_ = enabled;
self.button.enabled = enabled;
}
我的問題是,即使我在按鈕上設置enabled = NO
, TouchUpInside
仍會觸發處理程序。 我可以在處理程序中看到按鈕被禁用,但處理程序仍然被觸發。
請注意,有幾種方法可以解決這個問題 - 檢查處理程序中的button.enabled,@ sanchitsingh的答案等等。我想知道為什么會發生這種情況。
只需檢查代碼中是否包含任何手勢。 這可能會導致問題。 我想你應該用
button.enabled = NO;
button.userInteractionEnabled = NO;
根據我的個人經驗,來自這個問題 ,以及其他人在網絡上傳播,似乎Apple關於UIControl.enabled的文檔不正確,並且設置UIControl已禁用並不會阻止它獲取觸摸事件。 它只能中和一些事件,例如(從內存中,現在無法檢查)點擊,觸摸和當前動作觸發事件,因此您實際上必須使用UserInteractionEnabled屬性才能真正擺脫觸摸事件。
嘗試這個
button.userInteractionEnabled=NO;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.