iOS 关于可拖动的button

作者: Wo的小名叫单纯 | 来源:发表于2016-06-21 15:28 被阅读2023次

今天又是闲得蛋疼,研究一下关于button拖动事件,其实很简单,是需要几句话就可以,废话不多说,上代码

关于viewcontroller.h里面的东西

@property(nonatomic,strong)UIButton *button;

关于viewcontroller.m里面的东西
首先写viewDidLoad里面的

self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.button.frame = CGRectMake(100, 100, 50, 50);
    self.button.backgroundColor = [UIColor redColor];
    [self.button setTitle:@"触摸" forState:UIControlStateNormal];
    [self.button setTitle:@"移动" forState:UIControlEventTouchDown];
    [self.button addTarget:self action:@selector(dragMoving:withEvent: )forControlEvents: UIControlEventTouchDragInside];
    [self.button addTarget:self action:@selector(dragEnded:withEvent: )forControlEvents:UIControlEventTouchUpOutside];
    [self.button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.button];
    }

然后是方法

- (void) dragMoving: (UIControl *) c withEvent:ev
{
    c.center = [[[ev allTouches] anyObject] locationInView:self.view];
}

- (void) dragEnded: (UIControl *) c withEvent:ev
{
    c.center = [[[ev allTouches] anyObject] locationInView:self.view];
}

-(void)buttonAction:(UIButton *)sender
{
    NSLog(@"起飞");
}

好了,就是这么简单

相关文章

网友评论

  • 属鱼的加菲猫:楼主你的方法有问题,这样子加点击事件有冲突(我的解决方法是在按钮上加手势,来避免点击和拖拽冲突),并且你这个方法是之前有人发的 ,一摸一样,搬砖没注明出处,😒鄙视
    http://blog.csdn.net/qq5306546/article/details/8083402
    14b3a6ac00ba:@Wo的小名叫单纯 打脸嫌不嫌疼?是自己的就是自己的,不是自己的,就别诳人。https://gist.github.com/bacella/8628689 看看人家的代码,看看你的代码,还“很早以前就写得了”,多早?有四年吗?上面链接的代码,是四年前就写了的。
    属鱼的加菲猫:@Wo的小名叫单纯 嗯嗯
    Wo的小名叫单纯:@属鱼的加菲猫 这个是我很早以前就写得了,后来才传到这个上面
  • AutismGG:拖拽方法和点击事件会有冲突哦
    Wo的小名叫单纯:@且浮生若梦 这个太麻烦了,你直接给button 添加手势就解决了

本文标题:iOS 关于可拖动的button

本文链接:https://www.haomeiwen.com/subject/cvjgdttx.html