3

我一般用这种方法来实现UIButton可移动;

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

但它会同时触发 touchUpInside 事件,我需要 touchUpInside 事件来做一些其他的事情。

那么有人知道如何避免这种情况吗?

非常感谢;

使用下面的这些代码来解决它;

  [button addTarget:self action:@selector(touchDown:withEvent:) forControlEvents:UIControlEventTouchDown];

    [button addTarget:self action:@selector(touchDragInside:withEvent:) forControlEvents:UIControlEventTouchDragInside];
        [button addTarget:self action:@selector(touchUpInside:withEvent:) forControlEvents:UIControlEventTouchUpInside];

    - (void) touchUpInside :(UIControl*)c withEvent:ev{
    NSLog(@"touch Up inside");
    if (count) {
        NSLog(@"here I can do something about clicking event");
    }
}

    - (void) touchDown:(UIControl*)c withEvent:ev{
    NSLog(@"touch Down");
    count = YES;
}

    -(void) touchDragInside:(UIControl*)c withEvent:ev{
    NSLog(@"touch drag inside");
    c.center = [[[ev allTouches] anyObject] locationInView:self.view];
    count = NO;
}
4

1 回答 1

1

实际上,最好的方法是使用 UIPanGestureRecognizer 并将其添加到按钮中。它可以很好地处理拖动,您也可以点击它而无需做任何其他事情。

于 2016-08-25T11:05:30.790 回答