How to allow a user to move a button via iOS sdk

好久不见. 提交于 2019-12-04 17:01:10

You can have it done by using the action method -

//called on each instance during a drag event

- (IBAction)draggedOut: (id)sender withEvent: (UIEvent *) event {
    UIButton *selected = (UIButton *)sender;
    selected.center = [[[event allTouches] anyObject] locationInView:self.view];
} 

Since UIControl is a UIView, you can use addGestureRecognizer to install on you object a UIPanGestureRecognizer.

A UIGestureRecognizer allows a function you wrote to be called each time the specific gesture is executed on the view you attach the gesture recognizer to. You create one like this in your view controller viewDidLoad method:

-(void)viewDidLoad {
     ...
     gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDragOnButton)];
     [button addGestureRecognizer:gestureRecognizer];
     ...
     [super viewDidLoad];
}

This code will instantiate a gesture recognizer and attach it to your button. So, every gesture of kind "pan" (dragging) done on the button will cause a call to handleDragOnButton. In the code above, I assume that you your view controller contains declarations like:

@interface MyViewController : UIViewController {
    ...
    IBOutlet UIButton* button;   //-- this is created through IB
    UIPanGestureRecognizer* gestureRecognizer;   //-- this will be added by you
    ...
}    

Now, you need define a handleDragOnButton in your controller. In this function, you can get the current touch and move the button accordingly by changing its frame.

 - (void)handleDragOnButton:(UIPanGestureRecognizer*)recognizer {

    if (recognizer.state == UIGestureRecognizerStateBegan) {    

        CGPoint touchLocation = [recognizer locationInView:recognizer.view];

    } else if (recognizer.state == UIGestureRecognizerStateChanged) {    

            <your logic here>

    } else if (recognizer.state == UIGestureRecognizerStateEnded) {    

            <your logic here>

        }
  }

Don't forget to release the gesture recognizer in the controller's dealloc.

Look also at this doc from Apple.

An alternative could be using UIResponder's

 – touchesBegan:withEvent:
 – touchesMoved:withEvent:
 – touchesEnded:withEvent:
 – touchesCancelled:withEvent:

but I would only suggest that if you are targeting iOS 3.1.3 and older.

There is some open sourced code that does exactly that.

https://github.com/gmoledina/GMGridView

"A performant Grid-View for iOS (iPhone/iPad) that allows sorting of views with gestures (the user can move the items with his finger to sort them) and pinching/rotating/panning gestures allow the user to play with the view and toggle from the cellview to a fullsize display."

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