1

我有 2 个 uibutton 和 1 个标签,并且 longpressgesture 绑定到这些控件。当在任何控件上发生长按时,如何获取下面发生长按的对象是我编写的代码。

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];

下面是在 longpress 上调用的函数

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

如果我打印发件人的描述,那么我会得到

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

从中我怎样才能在发生长按事件时获得对象的引用我的意思是我如何知道我是否按下了 UiLabel 或 Uibutton?

4

2 回答 2

2

只需检查 UIGestureRecognizer 的(父类)视图属性:

@property(nonatomic, readonly) UIView *view

手势识别器附加到的视图。(只读)

@property(nonatomic, readonly) UIView *view Discussion 您使用 addGestureRecognizer: 方法将手势识别器附加(或添加)到 UIView 对象。

于 2012-08-15T18:36:13.820 回答
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.

    }


}
于 2012-08-16T04:41:32.547 回答