1

我一直在尝试通过覆盖 touchesMoved 方法在 iOS 中实现可拖动的 UIButton。按钮出现了,但是我无法拖动它。我在这里缺少什么? 这就是我提到的

这是我的 .h 文件。

 @interface ButtonAnimationViewController : UIViewController
 @property (weak, nonatomic) IBOutlet UIButton *firstButton;

还有 .m 文件。

@implementation ButtonAnimationViewController

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint pointMoved = [touch locationInView:self.view];
self.firstButton.frame = CGRectMake(pointMoved.x, pointMoved.y, 73, 44);

}
4

1 回答 1

0

在这里,您有一个完整的按钮拖动示例UIPanGestureRecognizer,在我看来,使用它更容易。我在发布代码之前对其进行了测试。如果您还有其他问题,请告诉我:

@interface TSViewController ()

@property (nonatomic, strong) UIButton *firstButton;

@end

@implementation TSViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // this code is just to create and configure the button
    self.firstButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.firstButton setTitle:@"Button" forState:UIControlStateNormal];
    self.firstButton.frame = CGRectMake(50, 50, 300, 40);
    [self.view addSubview:self.firstButton];

    // Create the Pan Gesture Recognizer and add it to our button
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragging:)];
    [self.firstButton addGestureRecognizer:panGesture];
}

// this method will be called whenever the user wants to drag the button
-(void)dragging:(UIPanGestureRecognizer*)panGesture {

    // if is not our button, return
    if (panGesture.view != self.firstButton) {
        return;
    }

    // if the gesture was 'recognized'...
    if (panGesture.state == UIGestureRecognizerStateBegan || panGesture.state == UIGestureRecognizerStateChanged) {

        // get the change (delta)
        CGPoint delta = [panGesture translationInView:self.view];
        CGPoint center = self.firstButton.center;
        center.x += delta.x;
        center.y += delta.y;

        // and move the button
        self.firstButton.center = center;

        [panGesture setTranslation:CGPointZero inView:self.view];
    }
}

@end

希望能帮助到你!

于 2013-09-26T19:10:23.313 回答