1

ドラッグを使用して、アプリで UIButton を移動したいと考えています。UIButton はコードを使用して作成されます。どうやってやるの?

4

3 に答える 3

5

次の方法でこれを達成できます。

touchesMovedジェスチャーを使用するか、使用できますUIPanGestureRecognizer

1) touchesMoved の使用:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    placardView.center = location;
   return;
}

2) 使用 UIPanGestureRecognizer

次のように、ジェスチャ認識エンジンをボタンに追加しviewDidLoadます。

UIPanGestureRecognizer *objGesture= [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveButton:)];
[myButton addGestureRecognizer:objGesture];
[objGesture release];

呼び出されるターゲットメソッドを書く

-(void)moveButton:(UIPanGestureRecognizer *)recognizer
{
if (recognizer.state == UIGestureRecognizerStateChanged || 
    recognizer.state == UIGestureRecognizerStateEnded) {

    UIView *draggedButton = recognizer.view;
    CGPoint translation = [recognizer translationInView:self.view];

    CGRect newButtonFrame = draggedButton.frame;
    newButtonFrame.origin.x += translation.x;
    newButtonFrame.origin.y += translation.y;
    draggedButton.frame = newButtonFrame;

    [recognizer setTranslation:CGPointZero inView:self.view];
}
}
于 2013-03-11T09:16:26.330 に答える
0
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
     CGPoint pt = [[touches anyObject] locationInView:self];
     button.center = pt;
}
于 2013-03-11T08:50:44.803 に答える
0

メソッドを使用するpanGestureRecognizerか、使用してみてください。touches詳細については、ここをクリックてください。

于 2013-03-11T09:04:12.663 に答える