您的当前位置:首页正文

iOS 关于可拖动的button

来源:图艺博知识网

今天又是闲得蛋疼,研究一下关于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(@"起飞");
}

好了,就是这么简单

Top