2011-09-09 19 views
8

我有幾個UIButtons的視圖。我已經成功實現了使用UILongPressGestureRecognizer和以下選擇器;在UILongPressGestureRecognizer上,我如何檢測哪個對象生成事件?

- (void)longPress:(UILongPressGestureRecognizer*)gesture { 
    if (gesture.state == UIGestureRecognizerStateEnded) { 
     NSLog(@"Long Press"); 
    } 
} 

我需要知道在這個方法是UIButton的接收長按,因爲我需要做不同的事情,這取決於哪個按鈕獲得了長按什麼。

希望答案不是映射長按發生位置的座標到按鈕邊界的某個問題 - 寧可不去那裏。

有什麼建議嗎?

謝謝!

回答

10

這可在gesture.view

1

如果您的視圖包含多個子視圖(如大量的按鈕),你可以決定什麼被竊聽:

// Get the position of the point tapped in the window co-ordinate system 
CGPoint tapPoint = [gesture locationInView:nil]; 

UIView *viewAtBottomOfHeirachy = [self.window hitTest:tapPoint withEvent:nil]; 

if ([viewAtBottomOfHeirachy isKindOfClass:[UIButton class]]) 
3

你加入長按手勢控制器具有UIButtons作爲子視圖UIView的?如果是這樣,那麼@Magic Bullet Dave的方法可能是一條路要走。

另一種方法是繼承UIButton併爲每個UIButton添加一個longTapGestureRecogniser。然後你可以讓你的按鈕做你喜歡的。例如,它可以向視圖控制器發送標識自己的消息。以下片段說明了子類的方法。

- (void) setupLongPressForTarget: (id) target; 
{ 
    [self setTarget: target]; // property used to hold target (add @property and @synthesise as appropriate) 

    UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:button action:@selector(longPress:)]; 
    [self addGestureRecognizer:longPress]; 
    [longPress release]; 
} 

- (void) longPress: (UIGestureRecognizer*) recogniser; 
{ 
    if (![recogniser isEnabled]) return; // code to prevent multiple long press messages 
    [recogniser setEnabled:NO]; 
    [recogniser performSelector:@selector(setEnabled:) withObject: [NSNumber numberWithBool:YES] afterDelay:0.2]; 

    NSLog(@"long press detected on button"); 

    if ([[self target] respondsToSelector:@selector(longPressOnButton:)]) 
    { 
     [[self target] longPressOnButton: self]; 
    } 
} 

在視圖控制器,你可能有一些代碼是這樣的:

- (void) viewDidLoad; 
{ 
    // set up buttons (if not already done in Interface Builder) 

    [buttonA setupLongPressForTarget: self]; 
    [buttonB setupLongPressForTarget: self]; 

    // finish any other set up 
} 

- (void) longPressOnButton: (id) sender; 
{ 
    if (sender = [self buttonA]) 
    { 
     // handle button A long press 
    } 

    if (sender = [self buttonB]) 
    { 
     // handle button B long press 
    } 

    // etc. 

} 
+0

如果([[個體經營目標] respondsToSelector:@selector(longPressOnButton :)]){ [自我目標] longPressOnButton:self]; } 這個if-block不能編譯...給錯誤:沒有已知的實例方法... – trillions

+0

我想通了...增加了一個協議,它修復了。謝謝.. – trillions

相關問題