【问题标题】:How to move UIView by longPress on button and then dragging?如何通过长按按钮然后拖动来移动 UIView?
【发布时间】:2013-10-10 18:17:52
【问题描述】:

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

}

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

【问题讨论】:

  • 你的意思是this
  • 是的,但是我该如何重新组织触摸事件呢?
  • 等等,在你的dragMoving 和dragBegan 方法中询问touch 的x 和y 值吗?如果是这样,请查看this
  • 我知道,但是如何在 UILongPressGestureRecognizer 中使用它?

标签: ios objective-c uiview long-press


【解决方案1】:

尝试使用此代码。我已经在我开发的纸牌游戏中使用了它。使用长按手势移动卡片。希望我能帮上忙。

 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
 }

【讨论】:

  • 你不懂!我需要长按按钮并拖动 MY_VIEW,同时触摸!
  • 你在 UIButton 上添加手势识别器,在 UIGestureRecognizerStateChanged 中你可以操作 MY_VIEW 的点
【解决方案2】:

我会使用@Coder404 提供的this link 来检测玩家是否使用了长按。然后,添加一个@property BOOL performedLongTouch 并将其设置为YES 中的selector 传递给UILongPressGestureRecognizer

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

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

【讨论】:

  • 移动需要长按再触摸,但我需要长按再移动!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多