Black Pearl
Black Pearl

Reputation: 93

How to move UIView by longPress on button and then dragging?

I want to move some UIView by button inside this view. I can it, in that way:

 - (void)viewDidLoad
    {
[button addTarget:self action:@selector(dragBegan:withEvent:) forControlEvents: UIControlEventTouchDown];
        [button addTarget:self action:@selector(dragMoving:withEvent:) forControlEvents: UIControlEventTouchDragInside];
        [button addTarget:self action:@selector(dragEnded:withEvent:) forControlEvents: UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
}

.

    - (void)dragBegan:(UIControl *)c withEvent:ev {

    UITouch *touch = [[ev allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];

}

- (void)dragMoving:(UIControl *)c withEvent:ev {
    UITouch *touch = [[ev allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
 //This is moving view to touchPoint
SimpleView.center = touchPoint;


}

- (void)dragEnded:(UIControl *)c withEvent:ev {

}

How can i move it only then, if I do longPress on that button?

Upvotes: 2

Views: 3837

Answers (2)

ReyJenald
ReyJenald

Reputation: 220

Try using this code. I've used this in a card game i developed. moving cards around using long press gestures. Hope i helps.

 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(addLongpressGesture:)];
 [longPress setDelegate:self];
 [YOUR_VIEW addGestureRecognizer:longPress];

- (void)addLongpressGesture:(UILongPressGestureRecognizer *)sender {

UIView *view = sender.view;

CGPoint point = [sender locationInView:view.superview];

if (sender.state == UIGestureRecognizerStateBegan){ 

  // GESTURE STATE BEGAN

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

 //GESTURE STATE CHANGED/ MOVED

CGPoint center = view.center;
center.x += point.x - _priorPoint.x;
center.y += point.y - _priorPoint.y;
view.center = center;

// This is how i drag my views
}

else if (sender.state == UIGestureRecognizerStateEnded){

  //GESTURE ENDED
 }

Upvotes: 8

doctorBroctor
doctorBroctor

Reputation: 2038

I would use this link provided by @Coder404 to detect whether or not the player used a long touch. Then, add an @property BOOL performedLongTouch and set that to YES in the selector passed into the UILongPressGestureRecognizer

Then, in your dragBegan and dragMoving functions, add a check for performedLongTouch and in your dragEnded function, set its value to NO

I know that seem pretty straight forward, but is that what you were looking for?

Upvotes: 1

Related Questions