【问题标题】:UILongPressGestureRecognizer issue with uibutton and uilabeluibutton 和 uilabel 的 UILongPressGestureRecognizer 问题
【发布时间】:2012-08-15 18:33:56
【问题描述】:

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

下面是长按调用的函数

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

如果我打印发件人的描述然后我得到

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

从中我怎样才能在发生 longpress 事件时获得对象的引用 我的意思是我怎么知道我按下的是 UiLabel 还是 Uibutton?

【问题讨论】:

    标签: iphone ios uibutton gesture


    【解决方案1】:

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

    @property(nonatomic, readonly) UIView *view

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

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

    【讨论】:

    • 如果是那么发件人没有查看属性我已经检查过了
    • 发件人的类别是什么?如果是 UILongPressGestureRecognizer,它应该有一个视图属性,因为它是 UIGestureRecognizer 的子类。
    • 没关系,我已经用这种方式解决了 UILongPressGestureRecognizer *gest = (UILongPressGestureRecognizer *)sender; UIView *v = gest.view;
    • 发送者为UILongPressGestureRecognizer,该属性继承自UIGestureRecognizer。这就是您在初始化 UILongPressGestureRecognizer 时分配选择器的方式。您对强制转换所做的只是让编译器忽略警告。您还可以声明该方法以接收 UIGestureRecognizer 对象,从而避免警告。所以,我原来的答案是正确的。
    • 对不起,我明白了,如果可能的话,你能举个例子吗?
    【解决方案2】:
    -(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.
    
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多