UIPanGestureRecognizer总是从位置移动(0,0)

时间:2014-05-31 06:24:45

标签: ios objective-c uipangesturerecognizer

我想拖动customView 但是,当我拖动customView时,它总是从位置(0,0)移动
请看下面的图像 红色部分是customView,当我拖动它时,它会移动到该位置。

enter image description here

如何修复它以正确移动customView? 我有这个代码。
labelview是customView(UIView的子类)。

- (void)viewDidLoad
{
    [super viewDidLoad];

    _labelView = [[LabelView alloc]initWithFrame:CGRectMake(20, 60, 200, 100)];
    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [_labelView addGestureRecognizer:pan];
    [self.view addSubview:_labelView];
}

- (void)panAction:(UIPanGestureRecognizer *)sender
{
    CGPoint p = [sender translationInView:self.view];
    CGPoint movedPoint = CGPointMake(_labelView.center.x + p.x, _labelView.center.y + p.y);
    sender.view.center = movedPoint;
    [sender setTranslation:movedPoint inView:self.view];
}

3 个答案:

答案 0 :(得分:2)

虽然其他两个答案技术上正确,但它们并不是理想的解决方案,因为当您向self.view添加手势识别器时,无论何时在self.view中任何位置拖动,您都会拖动你的LabelView,但我想你只想在你LabelView本身的手指上拖动它。

所以,只要保留你所拥有的,但改变这一行:

[sender setTranslation:movedPoint inView:self.view];

[sender setTranslation:CGPointZero inView:self.view];

答案 1 :(得分:0)

您已将逻辑颠倒过来。它必须完全相反。将'UIPanGestureRecognizer'设置为UIViewController的视图并设置自定义视图的中心。

- (void)viewDidLoad
{
    [super viewDidLoad];

    _labelView = [[LabelView alloc]initWithFrame:CGRectMake(20, 60, 200, 100)];
    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];

    // [_labelView addGestureRecognizer:pan]; must be removed

    [self.view addGestureRecognizer:pan]; // must be added

    [self.view addSubview:_labelView];
}

- (void)panAction:(UIPanGestureRecognizer *)sender
{
    CGPoint p = [sender translationInView:self.view];
    CGPoint movedPoint = CGPointMake(_labelView.center.x + p.x, _labelView.center.y + p.y);
    [_labelView setCenter:movedPoint];
}

答案 2 :(得分:0)

我通过编写以下代码解决了问题 谢谢你的回答。

- (void)viewDidLoad
{
    [super viewDidLoad];

    _labelView = [[LabelView alloc]initWithFrame:CGRectMake(20, 60, 200, 100)];
    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [_labelView addGestureRecognizer:pan];
    [self.view addSubview:_labelView];
}

- (void)panAction:(UIPanGestureRecognizer *)sender
{
    CGPoint p = [sender translationInView:sender.view];
    CGPoint movedPoint = CGPointMake(sender.view.center.x + p.x, sender.view.center.y + p.y);
    sender.view.center = movedPoint;
    [sender setTranslation:CGPointZero inView:sender.view];
}