UILongPressGestureRecognizer issue with uibutton and uilabel

风格不统一 提交于 2019-12-11 12:53:11

问题


i have 2 uibutton and 1 label and longpressgesture is bounded to these control. 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.

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

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


回答1:


Just check the UIGestureRecognizer's (the parent class) view property:

@property(nonatomic, readonly) UIView *view

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.




回答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.

    }


}


来源:https://stackoverflow.com/questions/11975022/uilongpressgesturerecognizer-issue-with-uibutton-and-uilabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!