如何通过长按按钮然后拖动来移动UIView?

时间:2013-10-10 18:17:52

标签: ios objective-c uiview long-press

我想在此视图中按下按钮移动一些UIView。 我可以这样做:

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

}

如果我按下那个按钮,我该如何移动呢?

2 个答案:

答案 0 :(得分:7)

尝试使用此代码。我在我开发的纸牌游戏中使用过它。使用长按手势移动卡片。希望我有所帮助。

 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
 }

答案 1 :(得分:1)

我会使用@ Coder404提供的this link来检测玩家是否长时间使用。然后,添加@property BOOL performedLongTouch并将其设置为传递到YES的{​​{1}}中的selector

然后,在UILongPressGestureRecognizerdragBegan函数中添加对dragMoving的检查,并在performedLongTouch函数中,将其值设置为dragEnded

我知道这看起来很简单,但那是你在找什么?