2015-05-14 62 views
1

嗨,我想獲得事件,當我觸摸已經選定的段。檢測事件時點擊已經選擇的片段

我已經實現了以下解決方案

import UIKit 

class MARSSegmentController: UISegmentedControl { 

    /* 
    // Only override drawRect: if you perform custom drawing. 
    // An empty implementation adversely affects performance during animation. 
    override func drawRect(rect: CGRect) { 
    // Drawing code 
    } 
    */ 

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
     let oldValue:NSInteger = self.selectedSegmentIndex 
     super.touchesBegan(touches, withEvent: event) 
     if oldValue == self.selectedSegmentIndex{ 
      sendActionsForControlEvents(UIControlEvents.ValueChanged) 
     } 
    }  
} 

這個工作正常,但ValueChanged事件得到,如果我攻非選擇分段執行兩次。

實施點按手勢不起作用。意味着當我點擊未選擇的片段時,它會在使用輕擊手勢時顯示舊的選定片段。

如果有任何解決方案,請提出建議。

+0

請原諒我,如果我錯了,但我認爲這將觸摸下來,並觸及。 – Tobias

+0

你可以先檢查UIEvent,如果它的值類型改變了,那麼不要調用sendActionsForControlEvents(UIControlEvents.ValueChanged) –

回答

0

我認爲你的問題在於if oldValue == self.selectedSegmentIndex將總是返回true的事實,因爲let oldValue:NSInteger = self.selectedSegmentIndex。所以你需要的是改變你的條件if oldValue == selectedValue其中selectedValue是你認爲選擇段的值

7

我意識到這是一個老問題,但我遇到了同樣的問題,我需要檢測現有段被選中以及選定的細分市場變化。

上面的解決方案很接近,但是這裏對我來說很有用。捕獲touchesBegan上的現有選定片段索引,然後在touchesEnded中將舊值與當前選定片段索引進行比較。如果它們相同,我手動觸發.ValueChanged事件。注意:這是Swift 2.0語法。

class SegmentedControlExistingSegmentTapped : UISegmentedControl 
{ 
    // captures existing selected segment on touchesBegan 
    var oldValue : Int! 

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) 
    { 
     self.oldValue = self.selectedSegmentIndex 
     super.touchesBegan(touches , withEvent: event) 
    } 

    // This was the key to make it work as expected 
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) 
    { 
     super.touchesEnded(touches , withEvent: event) 

     if self.oldValue == self.selectedSegmentIndex 
     { 
      sendActionsForControlEvents(.ValueChanged) 
     } 
    } 
} 
+0

謝謝!工作的完美 – jose920405

0

只有把self.nameSegmentedControl.isMomentary = true

用你的方法聯想到valueChanges,檢測水龍頭。