2011-04-14 74 views
1

對不起,如果這是一個基本問題,我找不到一個明確的答案。UIButton狀態改變不會發生,直到接觸結束

我已經設置了4個按鈕:

// Add the normal and selected state for each button 
UIImage *buttonImage = [UIImage imageNamed:[NSString stringWithFormat:@"HotspotNumber2-%i.png",(hotspotID +1)]]; 
[hotspotButton setImage:buttonImage forState:UIControlStateNormal]; 
UIImage *buttonImageSelected = [UIImage imageNamed:[NSString stringWithFormat:@"HotspotNumber2-%is.png",(hotspotID +1)]]; 
[hotspotButton setImage:buttonImageSelected forState:UIControlStateSelected]; 
[hotspotButton setImage:buttonImageSelected forState:UIControlStateHighlighted]; 
[hotspotButton addTarget:self action:@selector(hotspotTouch:) forControlEvents:UIControlEventTouchDown]; 

我陷阱的方法中的觸摸事件:

// Called when a hotspot is touched 
-(void)hotspotTouch:(id)sender{ 

    // Deselect the hotspot currently selected 
    if (selectedHotspot) [selectedHotspot setSelected:NO]; 

    selectedHotspot = (UIButton *)sender; 
    [selectedHotspot setSelected:YES]; 

    // Get dictionary of hot spot that is pressed 
    NSDictionary *hotspot = [hotspots objectAtIndex:[selectedHotspot tag]]; 
    NSString *imageFileName = [hotspot objectForKey:ksHotspotItemKey]; 
    if ([imageFileName length] > 0) currentImageView.image = [UIImage imageNamed:imageFileName]; 
    } 
} 

我的問題是,對於按鈕高亮顯示的圖像不顯示直到用戶釋放他們的手指,這是明顯的延遲。我已經看到其他人通過更改背景圖像而不是按鈕狀態或延遲後執行選擇器來解決類似的問題,因此運行循環有機會結束。這兩種方法對我來說似乎都是詭計,如果有人能夠解釋這裏發生的事情,以及實現這種效果的最可靠方法是什麼,只要用戶觸摸按鈕,它就會變爲突出顯示的狀態。

由於提前,

戴夫

+0

請僅嘗試使用UIControlEventTouchDown事件。 – Ravin 2011-04-14 11:00:33

+0

嗨Ravin,剛試過只TouchDown事件和相同的問題。如果觸地,方法會被調用,因爲主圖像被改變,但是按鈕狀態不會改變爲高亮顯示,直到您按下TouchUp或DragOutside按鈕的矩形。 – 2011-04-14 15:58:07

回答

1

有沒有發現周圍的工作。我爲TouchDown創建了一個方法,爲TouchUpInside和TouchUpOutside創建了一個方法。如果TouchDown已被選中並且改變我的視圖的圖像,TouchDown將簡單地取消選擇該按鈕。 TouchUp事件設置按鈕的選定屬性。由於突出顯示的圖像和選定的圖像都是相同的,所以淨效果是,只要觸摸按鈕,按鈕就會改變,並在觸摸事件發生後保持這種狀態。代碼在這裏:

// Called when a hotspot is touched down 
-(void)hotspotTouchDown:(id)sender{ 

    // Deselect the hotspot currently selected if it exists 
    if (selectedHotspot) [selectedHotspot setSelected:NO]; 

    // Get dictionary of hot spot that is pressed 
    NSDictionary *hotspot = [hotspots objectAtIndex:[sender tag]]; 

    // If the class of the hotspot is 'self' then replace the current image with a new one given in the hotspot data 
    if ([[hotspot objectForKey:ksHotspotClassKey] isEqualToString:ksHotspotClassSelf]) { 

     NSString *imageFileName = [hotspot objectForKey:ksHotspotItemKey]; 
     if ([imageFileName length] > 0) currentImageView.image = [UIImage imageNamed:imageFileName]; 
    } 
} 

// Called when a hotspot is touched up 
-(void)hotspotTouchUp:(id)sender{ 
    // Set the selected property of the button 
    selectedHotspot = (UIButton *)sender; 
    [selectedHotspot setSelected:YES]; 
}