简体   繁体   English

与uibutton和uilabel的UILongPressGestureRecognizer问题

[英]UILongPressGestureRecognizer issue with uibutton and uilabel

i have 2 uibutton and 1 label and longpressgesture is bounded to these control. 我有2个uibutton和1个标签,长压力限制在这些控制之下。 when longpress is taken place on any control then how to get the object on which longpress is taken place below is the code that i have written. 当在任何控件上进行longpress时,如何获得下面发生longpress的对象是我编写的代码。

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

below is function that is called on longpress 下面是在longpress上调用的函数

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

if i printing description of sender then i get 如果我打印发件人的描述然后我得到

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

from it how can i get the refrence of object on whcih longpress event takes place i mean how do i know whether i preessed UiLabel or Uibutton? 从中我怎么能得到长对象事件发生的对象的参考我的意思是我怎么知道我是否预言了UiLabel或Uibutton?

Just check the UIGestureRecognizer's (the parent class) view property: 只需检查UIGestureRecognizer(父类)视图属性:

@property(nonatomic, readonly) UIView *view @property(非原子,只读)UIView *视图

The view the gesture recognizer is attached to. 手势识别器附加到的视图。 (read-only) (只读)

@property(nonatomic, readonly) UIView *view Discussion You attach (or add) a gesture recognizer to a UIView object using the addGestureRecognizer: method. @property(非原子,只读)UIView *视图讨论使用addGestureRecognizer:方法将手势识别器附加(或添加)到UIView对象。

-(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.

    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM