ios - 接收 subview 的触摸事件

标签 ios uibutton subview touch-event eaglview

我有 BooksEAGLView 并且它有 UIButton 用于接收触摸事件。然后我的增强现实覆盖的目的是将覆盖 View 添加到 BooksEAGLView 然后我的按钮没有接收到触摸事件。

如何获取两个 View 的触摸事件。

bookOverlayController = [[BooksOverlayViewController alloc]initWithDelegate:self];

 // Create the EAGLView
 eaglView = [[BooksEAGLView alloc] initWithFrame:viewFrame delegate:self appSession:vapp];
 [eaglView addSubview:bookOverlayController.view];
 [self setView:eaglView];

 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
 return ([touch.view.superview isKindOfClass:[BooksEAGLView class]] || [touch.view.superview isKindOfClass:[TargetOverlayView class]]);
 }

触摸事件:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    NSLog(@"hitTest:withEvent called :");
    NSLog(@"Event: %@", event);
    NSLog(@"Point: %@", NSStringFromCGPoint(point));
    NSLog(@"Event Type: %d", event.type);
    NSLog(@"Event SubType: %d", event.subtype);
    NSLog(@"---");

    return [super hitTest:point withEvent:event];
}

最佳答案

好的,我专门为你做了示例项目。这是我所做的:

  • 子类化 UIView 类并创建 CustomView。
  • 在 Storyboard 的 Identity inspector 部分将 View 的 Class 设置为 CustomView

enter image description here

在屏幕截图上,您可能会注意到 View 层次结构,它重复了您的概念。

这里在 CustomView.m 中覆盖了 hitTest:withEvent:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (!self.clipsToBounds && !self.hidden && self.alpha > 0) {
        for (UIView *subview in self.subviews.reverseObjectEnumerator) {
            CGPoint subPoint = [subview convertPoint:point fromView:self];
            UIView *result = [subview hitTest:subPoint withEvent:event];
            if (result != nil && [result isKindOfClass:[UIButton class]]) {
                return result;
            }
        }
    }

    return [super hitTest:point withEvent:event];
}

该方法通过调用每个 subview 的pointInside:withEvent: 方法来遍历 View 层次结构,以确定哪个 subview 应该接收触摸事件。如果 pointInside:withEvent: 返回 YES,则类似地遍历 subview 的层次结构,直到找到包含指定点的最前面的 View 。如果 View 不包含该点,则忽略其 View 层次结构的分支。您很少需要自己调用此方法,但您可以覆盖它以从 subview 中隐藏触摸事件。 此方法忽略隐藏的 View 对象、已禁用用户交互或 alpha 级别小于 0.01 的 View 对象。此方法在确定命中时不考虑 View 的内容。因此,即使指定的点位于该 View 内容的透明部分,仍然可以返回该 View 。

关于甜点:Sample Project

关于ios - 接收 subview 的触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22910347/

相关文章:

ios - 按钮框架在运行时变化

ios - 具有异步图像加载的自调整单元格大小

ios - iOS 上 NSFileHandle 的文件路径(Swift 或 Objective-C)

iphone - 绘制动画

ios - 架构 arm64 : "_OBJC_CLASS_$_PFUser", 的 undefined symbol 引用自:

swift - 如何在 SKScene 中正确设置 UIButton

iPhone iOS 如何向按钮文本或图像下的 UIButton 添加线性渐变?

ios - 如何在不重新加载的情况下从 super View 中删除 View ?

iOS viewDidLoad 未被触发

ios - 将 UIImageView 添加到 subview