代码之家  ›  专栏  ›  技术社区  ›  some_id

UIButton上的UITapGestureRecognizer

  •  4
  • some_id  · 技术社区  · 15 年前

    我有一个UIButton,它有一个IBAction,还有一个UITapGestureRecognizer来检测双点击。

    编辑

    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleDoubleTap:)];
    [doubleTap setNumberOfTapsRequired:2];
    [A1 addGestureRecognizer:doubleTap];
    [A2 addGestureRecognizer:doubleTap];
    [B1 addGestureRecognizer:doubleTap];
    
    1 回复  |  直到 14 年前
        1
  •  4
  •   Iulian Onofrei Denis Oliveira    8 年前

    看起来您正试图将一个手势识别器附加到多个按钮。手势识别器一次只能附加到一个视图。因此,在您的情况下,您连接识别器的最后一个按钮(按钮B1)可能响应双击,但A1和A2不响应。

    为每个按钮创建单独的识别器。
    但这三个识别器都可以调用相同的操作方法( handleDoubleTap:

    然而,当你尝试点击一个按钮时,会有一个轻微的延迟,因为它会等待看是否是双击的开始。有很多方法可以减少延迟,但如果你能忍受延迟,并且解决方案会带来其他问题,那么这可能是不值得的。

    编辑:
    在你的评论中,你说你“想知道他们是否同时被按下”。为此,您不需要手势识别器。您可以只使用提供的标准控件事件。

    下一步,在IB,为了 按钮,连接“触地”事件 buttonPressed: . 或者,要以编程方式执行此操作:

    [button1 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
    [button2 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
    [button3 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
    

    每个 按钮,连接“内部修补” “外部装修”活动 buttonReleased:

    [button1 addTarget:self action:@selector(buttonReleased:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
    [button2 addTarget:self action:@selector(buttonReleased:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
    [button3 addTarget:self action:@selector(buttonReleased:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
    

    接下来,添加ivar以跟踪按下了多少个或哪些按钮:

    @property (nonatomic) int numberOfButtonsBeingTouched;
    @property (strong, nonatomic) NSMutableSet *buttonsBeingTouched; //alloc + init in viewDidLoad or similar
    

    如果你只关心按下了多少按钮,你就不需要 NSMutableSet

    最后,添加buttonPressed和buttonRelease方法:

    - (IBAction)buttonPressed:(UIButton *)button {
        self.numberOfButtonsBeingTouched++;
        [self.buttonsBeingTouched addObject:button];
        //your logic here (if (self.numberOfButtonsBeingTouched == 3) ...)
    }
    
    - (IBAction)buttonReleased:(UIButton *)button {
        self.numberOfButtonsBeingTouched--;
        [self.buttonsBeingTouched removeObject:button];
        //your logic (if any needed) here
    }