How do you get the touchesBegan coordinates when a UIButton is triggered?

后端 未结 2 1950
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 22:14

I have a touchesBegan method set up to pick up the coordinates when the user touches the screen. It works great except when I touch down on a UIButton. How do I make it so

相关标签:
2条回答
  • 2020-12-23 22:29

    Try overriding UIButton class and in the touchesBegan method call [super touchesBegan..].

    0 讨论(0)
  • 2020-12-23 22:42

    Add event handlers to the button, something like the following,

    [myButton addTarget:self action:@selector(dragBegan:withEvent:) forControlEvents: UIControlEventTouchDown];
    [myButton addTarget:self action:@selector(dragMoving:withEvent:) forControlEvents: UIControlEventTouchDragInside];
    [myButton addTarget:self action:@selector(dragEnded:withEvent:) forControlEvents: UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
    

    Handle the events as the following, you can get the touch point from the event ev as below,

    - (void)dragBegan:(UIControl *)c withEvent:ev {
        NSLog(@"dragBegan......");
        UITouch *touch = [[ev allTouches] anyObject];
        CGPoint touchPoint = [touch locationInView:self.view];
        NSLog(@"Touch x : %f y : %f", touchPoint.x, touchPoint.y);
    }
    
    - (void)dragMoving:(UIControl *)c withEvent:ev {
        NSLog(@"dragMoving......");
    }
    
    - (void)dragEnded:(UIControl *)c withEvent:ev {
        NSLog(@"dragEnded......");
    }
    

    This is not my own answer. I got this code from http://sree.cc/iphone/handling-touche-events-for-uibuttons-in-iphone and made some minor changes.

    0 讨论(0)
提交回复
热议问题