我试图让一些UIButton
对自己的看法一个实例被感动,并在屏幕上拖动(最终与气势,但那是以后!)。 我有这个工作在一个非常简单的形式,如下图所示,但问题是,通过触摸按钮,开始拖动它,它附着在手指上,将手指抬起关闭时,将触发“触摸的内心”活动,这是我想在实际敲击按钮时执行的代码。
概括地说:我怎么水龙头和拖动/释放区分? 我是否需要抽头变换短抽头手势识别,或类似的,也许? 码:
在viewDidLoad中:
[firstButton addTarget: self action: @selector(wasDragged: withEvent:) forControlEvents: UIControlEventTouchDragInside];
而我wasDragged方法:
- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{
if (button == letter1Button) {
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
并告诉它取消触摸鉴于...
- (void)viewDidLoad
{
[super viewDidLoad];
UIPanGestureRecognizer *panRecognizer;
panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
action:@selector(wasDragged:)];
// cancel touches so that touchUpInside touches are ignored
panRecognizer.cancelsTouchesInView = YES;
[[self draggableButton] addGestureRecognizer:panRecognizer];
}
- (void)wasDragged:(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];
}
- (IBAction)buttonWasTapped:(id)sender {
NSLog(@"%s - button tapped",__FUNCTION__);
}
对于像我这样的初学者,我试图UIPanGestureRecognizer
按照以上建议,但没有奏效。 所以,这里是我的简单的解决办法:首先,添加事件侦听器通过贝格的建议:
// add drag listener
[button addTarget:self action:@selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];
// add tap listener
[button addTarget:self action:@selector(wasTapped:) forControlEvents:UIControlEventTouchUpInside];
这两个阻力和自来水都将触发UIControlEventTouchUpInside
,所以在添加一个标志wasDragged:withEvent:
是这样的:
-(IBAction)wasDragged: (id)sender withEvent: (UIEvent *) event {
was_dragged = YES;
UIButton *selected = (UIButton *)sender;
selected.center = [[[event allTouches] anyObject] locationInView:self.view];
}
- (IBAction)buttonWasTapped:(id)sender {
if(!was_dragged)
NSLog(@"button tapped");
else{
was_dragged = NO;
NSLog(@"button dragged");
}
}
瞧。 完成。
使用类似的UIButton的UIControlEventTouchDragInside和UIControlEventTouchUpInside事件
// add drag listener
[button addTarget:self action:@selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];
// add tap listener
[button addTarget:self action:@selector(wasTapped:) forControlEvents:UIControlEventTouchUpInside];
您可以使用HBDraggableButton控制..
文章来源: Touch and drag a UIButton around, but don't trigger it when releasing the finger