ios - 如何使用 touchesBegan 和 touchesEnded 检测点击手势

标签 ios objective-c cocoa-touch

我创建了一个自定义控件,它直接派生自 UIView 类。现在我想在用户点击我 View 的特定部分时执行一个操作。所以我重写了方法 touchesBegantouchesEndedtouchesCancelled。问题是,如果我只是点击显示屏,方法 touchesEnded 永远不会被调用。 touchesCancelled 方法被称为它的替代品。 touchesEnded 仅在我执行某些手势(滑动、移动等)时被调用。

我是否需要以任何方式配置我的 View 以启用点击手势?

我的代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesBegan");
    self->touchDown = YES;
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        self.value = 1.0;
    } completion:nil];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (self->touchDown) {
        NSLog(@"touchesEnded");
        self->touchDown = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.value = 0.0;
        } completion:nil];
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    if (self->touchDown) {
        NSLog(@"touchesCancelled");
        self->touchDown = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.value = 0.5;
        } completion:nil];
    }
}

对于点击手势,我得到:

2018-07-17 09:55:20.994645+0200 iOS Test[33049:2763212] touchesBegan

2018-07-17 09:55:21.092409+0200 iOS Test[33049:2763212] touchesCancelled

最佳答案

您是否尝试过在您的 View 上设置recognizer.cancelsTouchesInView = NO;

A Boolean value affecting whether touches are delivered to a view when a gesture is recognized.

关于ios - 如何使用 touchesBegan 和 touchesEnded 检测点击手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51376735/

相关文章:

ios - 带有一个可见单元格 : determine which is most visible 的 UITableView

iOS:后台线程/多线程?

ios - 如何为我的 iOS Cocos2d 游戏保存游戏数据?

ios - 如何摆脱 UIToolBar 中我的按钮顶部的线

ios - 在iOS 10.0中获取唯一的设备ID

iOS 9 启动服务 : ERROR: There is no registered handler for URL scheme itms-services

ios - Xcode On Archive 验证配置文件冲突

ios - 旋转 View Controller

ios - MKPointAnnotation 表达式不可分配

ios - CLLocationManager monitoredRegions (NSSet) 不正确,或者其他原因?