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];
}
网友评论