在屏幕中移动一个按钮

时间:2011-05-17 09:31:20

标签: iphone objective-c cocoa-touch

我有UIButton,我想通过触摸并在屏幕上滑动来移动该按钮。当我松开触摸时,它将处于当前位置。请解释清楚。

3 个答案:

答案 0 :(得分:2)

您可以使用触摸移动事件移动视图。 Apple提供了一个示例教程MoveMe,可以拖动视图,并在发布触摸后为视图设置动画。特别检查MoveMeView.m中的触摸事件(touchesBegan,touchesMoved,touchesEnded),了解他们如何移动placardView。您可以像placardView一样移动按钮。

取自'drag' move a uibutton so it acts like uiScrollView

答案 1 :(得分:2)

检查this

你应该从点移动框架并相应地移动框架,以便你的按钮在触摸位置移动

答案 2 :(得分:1)

如果您是iOS 3.2及更高版本的脚本,请考虑使用UIPanGestureRecognizer

只需附上一个像这样的实例,

...
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
panGesture.maximumNumberOfTouches = 1;
panGesture.minimumNumberOfTouches = 1;

[self.button addGestureRecognizer:panGesture];
[panGesture release];
...

并像这样定义handlePan:

- (void)handlePan:(UIPanGestureRecognizer *)panGesture {
    CGRect buttonFrame = self.button.frame;
    CGPoint translation = [panGesture translationInView:panGesture.view];

    buttonFrame.origin.x += translation.x;
    buttonFrame.origin.y += translation.y;

    [panGesture setTranslation:CGPointMake(0, 0) inView:panGesture.view];
    self.button.frame = buttonFrame;
}