Creating a draggable button

I have no problem having a draggable image, but when it comes to having a button draggable it is unable to drag. With the code I used below can someone please help me solve my problem, thank you in advance.


.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController{

    IBOutlet UIButton *button;+
}
@end


.m

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *myTouch = [[event allTouches] anyObject];
    CGPoint location = [myTouch locationInView:self.view];
   
    if ([myTouch view] == button){
        button.center = location;
    }
   
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self touchesBegan:touches withEvent:event];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    /
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    /
}
@end
Answered by PBK in 202706022

The problem is that the button is picking up the touch event and not sending it to your touchesbegan or touchesMove methods. You will need to disable the button and then in touchesBegan sense that the touch is in the area of the button. Note, [event allTouches] has nothing to do with your button - it refers to the multiple fingers in a touch event and their location in the view.


Here is some code that will be useful for you:


to start the move experience:

myButton.enabled=NO;

in touchesBegan:

if(CGRectContainsPoint(myButton.frame, [myTouch locationInView:myView])){

Seen this older example?


h t t p s : / / www.cocoanetics.com/2010/11/draggable-buttons-labels/

Accepted Answer

The problem is that the button is picking up the touch event and not sending it to your touchesbegan or touchesMove methods. You will need to disable the button and then in touchesBegan sense that the touch is in the area of the button. Note, [event allTouches] has nothing to do with your button - it refers to the multiple fingers in a touch event and their location in the view.


Here is some code that will be useful for you:


to start the move experience:

myButton.enabled=NO;

in touchesBegan:

if(CGRectContainsPoint(myButton.frame, [myTouch locationInView:myView])){

One more thing - that cute code where you do your thing in touchesBegan and then call it in touchesMoved is a debugging nightmare tragedy waiting to happen. There is no need to do anything in touchesbegan other than to set variables for the call to touchesMoved. Do your thing in touchesMoved.

Creating a draggable button
 
 
Q