ios - 在主视图中处理touchesBegan - 如何获取触摸的 subview ?

标签 ios iphone uiscrollview hittest touchesbegan

在单个 View iPhone应用程序中,我具有以下结构:scrollView -> contentView -> imageView,并且在下面(在主视图处)有7个可拖动的自定义 View - 可以从/拖动到 contenView

最初拖动是在自定义 View 中处理的(请参阅 Tile.m@2eb672523a ),虽然效果很好,但需要向主视图发送通知。

因此,我尝试将 touchesBegan 和好友移至主应用 View (请参阅 ViewController.m )。

我的问题是:

最初,我在 contentView 中添加了以下代码(请参阅 GameBoard.m ),以在 scrollView 上启用 subview 拖动:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView* result = [super hitTest:point withEvent:event];

    return result == self ? nil : result;
}

但是,当尝试将图 block 从 contentView 拖回到主视图时(按照下面屏幕截图所示的方向),这不会将 touchesBegan 传递到主视图查看。

app screenshot

所以我更改了此方法以返回主视图而不是图 block :

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView* result = [super hitTest:point withEvent:event];

    return result == self ? nil : self.window.rootViewController.view;
}

现在在主视图上调用了 touchesBegan (正如我在调试器中看到的那样),但是 touches.view 也指向主视图。

我的问题是:

如何在新的 touchesBegan 方法中找到触摸的图 block ?

最佳答案

没关系,我已经解决了我的问题。

ViewController.m我添加了一个 _draggedTile ivar 并通过使用以下方法在 touchesBegan 中设置它来查找触摸的图 block :

- (SmallTile*) findTileAtPoint:(CGPoint)point withEvent:(UIEvent*)event
{
    NSArray* children = [self.view.subviews arrayByAddingObjectsFromArray:_contentView.subviews];

    for (UIView* child in children) {
        CGPoint localPoint = [child convertPoint:point fromView:self.view];

        if ([child isKindOfClass:[SmallTile class]] &&
            [child pointInside:localPoint withEvent:event]) {
            return (SmallTile*)child;
        }
    }

    return nil;
}

touchedMovedtouchesEndedtouchesCancelled 中,我只使用该 ivar(最初我使用的是上面的 findTileAtPoint:withEvent: 方法也有,但有时触摸不会完全位于拖动的图 block 上,并且移动会不稳定或被取消)。

关于ios - 在主视图中处理touchesBegan - 如何获取触摸的 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22781755/

相关文章:

iphone - iOS 核心数据对象的唯一标识符?

iOS:在选择顶部文本字段时阻止 ScrollView 腾出空间

ios - 如何在 Interface Builder 中存储键/值并在运行时访问它们?

objective-c - 我们可以覆盖 Objective-C 中的 alloc 和 dealloc 吗?

ios - 查看选择了哪些对象的神奇命令

iphone - 放大CATiledLayer时如何在未转换的上下文上绘制?

ios - UIPageViewController 内的 UIScrollView 重叠。错误与否?

ios - 无法在自定义 TableView 单元类的 bundle 中加载 NIB

iphone - 警告 - 在协议(protocol)中找不到版本

iphone - 如何在 iOS 中按修改日期对文件进行排序