iOS UIButton 拖动事件

作者: 唐人街的乞丐 | 来源:发表于2020-09-17 15:42 被阅读0次

UIButton 添加添加拖动事件

    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(200, 200, 50, 50);
    button.backgroundColor = [UIColor redColor];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(dragMoving:withEvent:)forControlEvents: UIControlEventTouchDragInside];
- (void)dragMoving:(UIControl *)control withEvent:event
{
    control.center = [[[event allTouches] anyObject] locationInView:self.view];
}

也可以

[button addTarget:self action:@selector(dragMoving:withEvent:)forControlEvents: UIControlEventTouchDragInside];


- (void)dragMoving:(UIButton *)button withEvent:(UIEvent *)event
{
        UITouch *touch = [[event touchesForView:button] anyObject];
        CGPoint previousLocation = [touch previousLocationInView:button];
        CGPoint location = [touch locationInView:button];
        CGFloat delta_x = location.x - previousLocation.x;
        CGFloat delta_y = location.y - previousLocation.y;
        button.center = CGPointMake(button.center.x + delta_x, button.center.y + delta_y);
}

如果不想拖动事件和按钮点击事件冲突,可以用
UIPanGestureRecognizer

如果不想要按钮滑动到边界,可以在(buttonMoving:)方法里面对坐标进行判断。

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(buttonMoving:)];
        panRecognizer.cancelsTouchesInView = YES;
[button addGestureRecognizer:panRecognizer];




- (void)buttonMoving:(UIPanGestureRecognizer *)recognizer {
    UIButton *button = (UIButton *)recognizer.view;
    CGPoint translation = [recognizer translationInView:button];
    button.center = CGPointMake(button.center.x + translation.x, button.center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:button];
}

相关文章

网友评论

    本文标题:iOS UIButton 拖动事件

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