简体   繁体   English

如何在iOS 6中实现可拖动的UIButton?

[英]How to implement dragable UIButton in iOS 6?

I have been trying to implement dragable UIButton in iOS by overriding touchesMoved method. 我一直在尝试通过覆盖touchesMoved方法在iOS中实现可拖动的UIButton。 The button shows up , however i am not able to drag it.What am i missing here? 该按钮显示出来,但是我无法拖动它。我在这里缺少什么? this is what i reffered 这就是我所推荐的

This is my .h file. 这是我的.h文件。

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

And the .m file. 和.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);

}

Here you have a fully working button dragging example using UIPanGestureRecognizer which, in my opinion, is easier. 在这里,您有一个使用UIPanGestureRecognizer的完全正常的按钮拖动示例,我认为这更容易。 I tested it before posting the code. 我在发布代码之前对其进行了测试。 Let me know if you have any more questions: 如果您还有其他问题,请告诉我:

@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

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM