简单拖动;放弃观看?

时间:2012-11-12 22:21:08

标签: ios

我正在学习iOS,但我找不到如何将拖放行为添加到UIView

我试过了:

[_view addTarget:self action:@selector(moved:withEvent:) forControlEvents:UIControlEventTouchDragInside];

它说“UIView没有可见的界面声明选择器addTarget (etc)

此外,我尝试添加平移手势识别器,但不确定这是否是我需要的

- (IBAction)test:(id)sender {
       NSLog(@"dfsdfsf");
  }

它被调用,但不知道如何获取事件的坐标。在iOS中注册移动事件的回调/拖放是不是标准的简单方法?

提前致谢。

2 个答案:

答案 0 :(得分:15)

UIPanGestureRecognizer肯定是要走的路。如果您希望用户拖动视图,您需要在superview的坐标系中进行手势的“翻译”(移动):

- (IBAction)panWasRecognized:(UIPanGestureRecognizer *)recognizer {
    CGPoint translation = [recognizer translationInView:_view.superview];

完成翻译后,您可以通过更改其center来移动(“拖动”)视图:

    CGPoint center = _view.center;
    center.x += translation.x;
    center.y += translation.y;
    _view.center = center;

最后,您要将平移手势识别器的翻译设置回零,因此下次收到消息时,它只会告诉您自上一条消息以来手势移动了多少:

    [recognizer setTranslation:CGPointZero inView:_view.superview];
}

这里可以轻松复制/粘贴:

- (IBAction)panWasRecognized:(UIPanGestureRecognizer *)recognizer {
    CGPoint translation = [recognizer translationInView:_view.superview];

    CGPoint center = _view.center;
    center.x += translation.x;
    center.y += translation.y;
    _view.center = center;

    [recognizer setTranslation:CGPointZero inView:_view.superview];
}

答案 1 :(得分:4)

touchesBegantouchesMovedtouchesEnded开始。在你的UIView子类中覆盖这些,你将开始学习事件系统。您可以像这样获取事件坐标:

- (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event
{
    float x = [[touches anyObject] locationInView:self].x;
    float y = [[touches anyObject] locationInView:self].y;
}

然后有很多东西用于转换不同视图之间的坐标等等。一旦你理解了这一点,你就可以使用你已经找到的UIGestureRecognizer这些你需要的东西。

您需要使用平移手势识别器进行拖放操作。您可以使用locationInView:中的UIPanGestureRecognizer选择器查找您在任何特定时刻的位置。

您可以像这样添加手势识别器,而不是添加您尝试的目标操作:

UIPanGestureRecognizer *dragDropRecog = [[UIPanGestureRecognizer alloc] initWithTarget:yourView action:@selector(thingDragged:)];
[yourView addGestureRecognizer:dragDropRecog];

然后,您必须在视图中实现选择器thingDragged:

- (void) thingDragged:(UIPanGestureRecognizer *) gesture
{
    CGPoint location = [gesture locationInView:self];
    if ([gesture state] == UIGestureRecognizerStateBegan) {
        // Drag started
    } else if ([gesture state] == UIGestureRecognizerStateChanged) {
        // Drag moved
    } else if ([gesture state] == UIGestureRecognizerStateEnded) {
        // Drag completed
    }
}

您将翻译在更改的位中拖动的视图,并处理已结束部分中的拖放。