2

我想在这个视图中通过按钮移动一些 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 {

}

如果我长按那个按钮,我怎么才能移动它?

4

2 回答 2

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
 }
于 2013-10-11T03:21:56.147 回答
1

我会使用@Coder404 提供的这个链接来检测玩家是否使用了长按。然后,添加一个@property BOOL performedLongTouch并将其设置为YES传入selectorUILongPressGestureRecognizer

然后,在您的dragBegananddragMoving函数中,添加一个检查performedLongTouchand 在您的dragEnded函数中,将其值设置为NO

我知道这看起来很简单,但这就是你要找的吗?

于 2013-10-10T23:23:59.057 回答