2012-08-15 199 views
1

我有2個uibutton和1個標籤,並且longpressgesture與這些控件有界。當longpress發生在任何控件上時,如何獲得longpress發生在下面的對象是我寫的代碼。UILongPressGestureRecognizer與uibutton和uilabel問題

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
btn.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
[btn addTarget:self action:@selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside]; 
//[self.view addSubview:btn]; 
btn.userInteractionEnabled = YES; 

// add it 
[self.view addSubview:btn]; 
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] 
              initWithTarget:self 
              action:@selector(handleLongPress:)]; 
longPress.minimumPressDuration = 1.0; 
[btn addGestureRecognizer:longPress]; 
下面

是叫上長按

-(void)handleLongPress:(id)sender{ 
} 

如果我打印發送者的描述功能,然後我得到

<UILongPressGestureRecognizer: 0x6aa4480; state = Began; view = <UIRoundedRectButton 0x6aa9570>; target= <(action=handleLongPress:, target=<ViewController 0x6a8cc60>)>> 

從中我怎樣才能對象上whcih的refrence longpress事件發生 我的意思是我如何知道我是否preessed UiLabel或Uibutton?

回答

2

只需選中UIGestureRecognizer的(父類)視圖屬性:

@屬性(非原子,只讀)的UIView *視圖

手勢識別連接到的視圖。 (只讀)

@屬性(非原子,只讀)的UIView *視圖 討論 您連接(或添加)使用addGestureRecognizer手勢識別到一個UIView對象:方法。

+0

u mean mean sender.view? – KsK 2012-08-15 18:39:00

+0

如果它然後發件人沒有視圖屬性我已經檢查過它 – KsK 2012-08-15 18:39:46

+1

什麼是發件人的類?如果它是UILongPressGestureRecognizer,它應該有一個視圖屬性,因爲它是UIGestureRecognizer的子類。 – J2theC 2012-08-15 18:42:26

1
-(void)handleLongPress:(UILongPressGestureRecognizer *)sender{ 


    if ([sender.view isKindOfClass:[UIButton class]]) { 

      UIButton *myButton = (UIButton *)sender.view; // here is your sender object or Tapped button 

      if (myButton.tag == 1) { 

        //sender is first Button. Because we assigned 1 as Button1 Tag when created. 
      } 
      else if (myButton.tag == 2){ 

        //sender is second Button. Because we assigned 2 as Button2 Tag when created. 
      } 
    } 

    if ([sender.view isKindOfClass:[UILabel class]]) { 

     UILabel *myLabel = (UILabel *)sender.view; // here is your sender object or Tapped label. 

    } 


} 
+0

使用此作爲您的發件人.. – 2012-08-16 04:42:44