2014-02-14 44 views
1

今天,我試圖將其他UILongPressGestureRecognizer添加到UISwitch,這實際上並不奏效。我的代碼是下面的:UISwitch上的UILongPressGestureRecognizer不會觸發

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(doSomething:)]; 
[lpgr setDelaysTouchesBegan:YES]; 
[lpgr setDelaysTouchesEnded:YES]; 
[lpgr setCancelsTouchesInView:YES]; 
[self.switcher addGestureRecognizer:lpgr]; 
viewController那就是開關的父 viewControllerviewDidLoad方法

。 (切換器是一個實例變量,通過故事板設置。IBOutlet從UISwitch正確設置到其viewController的switcherProperty)。

在其他一些控件(如UIButton, UISlider, UIStepper等)上,即使沒有觸摸取消或延遲,也可以完美觸發目標方法。但是,用我的開關,它拒絕了這種行爲。

我試圖通過所有gestureRecognizers該交換機上進行迭代,並呼籲消除[switcher removeGestureRecognizer: ... ]任何其他gestureRecognizer在UISwitch,從來就還設置他們都要求我longPressGestureRecognizer失敗。其他類型的gestureRecognizers也不會觸發。

就我所知,GestureRecognizers將在它們所屬的視圖或控件之前接收觸摸,並接收它們。因此,setCancelsTouchesInView:YESsetDelaysTouchesInView:YES應該啓用gestureRecognizer來處理每一個手勢,直到它失敗或成功,沒有視圖知道,對嗎?

--------------編輯------------------

我的方法的全部內容:

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

UIGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(edit:)]; 
[self.view addGestureRecognizer:lpgr]; 

lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(edit:)]; 
[self.button addGestureRecognizer:lpgr]; 

lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(edit:)]; 
[self.slider addGestureRecognizer:lpgr]; 

lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(edit:)]; 
[self.segmentedControl addGestureRecognizer:lpgr]; 

lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(edit:)]; 
[self.switcher addGestureRecognizer:lpgr]; 

lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(edit:)]; 
[self.stepper addGestureRecognizer:lpgr]; 
} 

正如我所說的,這是工作的其他控件,只有開關不想工作

+1

我猜問題在這裏:[self.switcher setUserInteractionEnabled:NO];您禁用了交互,這可能(我不是絕對確定的)也會影響手勢識別器。 – manecosta

+0

對不起,其實這只是一個測試後,我嘗試沒有這一行。它以前沒有工作 – TAKeanice

回答

0

嘗試用它

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { 

// Disallow recognition of tap gestures in the segmented control. 
if ((touch.view == yourSwitch)) {//change it to your condition 
    return NO; 
} 
return YES; 
} 

請務必確認UIGestureRecognizerDelegate它的工作。

+0

爲什麼我不應該讓gestureRecognizer接收我的觸摸?這與我想要的完全相反。連接到我的交換機的我的gestureRecognizer不會收到它應該接收的觸摸。我沒有爲我的gestureRecognizer設置委託,如果方法未實現,則默認值爲YES。 – TAKeanice

+0

另外,我沒有UISwitch的子類,所以如果我想成爲其他gestureRecognizers的代表,我將不得不設置它們的委託。這應該與完全刪除它們的效果相同,我嘗試過。 – TAKeanice