我想使用拖动在我的应用中移动UIButton。 UIButton是使用代码创建的。 我怎么能这样做?
答案 0 :(得分:4)
你可以通过以下方式实现这一目标:
您可以使用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];
}
}
答案 1 :(得分:0)
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint pt = [[touches anyObject] locationInView:self];
button.center = pt;
}
答案 2 :(得分:0)
尝试使用panGestureRecognizer
或使用touches
方法。
点击here以获取更多参考资料。