【问题标题】:Handling touchesBegan in the main view - how to get ahold of the touched subview?在主视图中处理 touchesBegan - 如何获取被触摸的子视图?
【发布时间】:2014-04-01 09:28:34
【问题描述】:

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

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

所以我正在尝试将touchesBegan 和朋友移动到主应用视图(请参阅ViewController.m)。

我的问题是:

最初我在contentView 中有这段代码(请参阅GameBoard.m),以便在scrollView 处启用子视图拖动:

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

    return result == self ? nil : result;
}

但是,当尝试将磁贴从 contentView 拖回主视图时(按以下屏幕截图所示的方向),这不会将 touchesBegan 传送到主视图。

所以我改变了这个方法来返回主视图而不是图块:

- (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 方法中找到被触摸的磁贴?

【问题讨论】:

    标签: ios iphone uiscrollview hittest touchesbegan


    【解决方案1】:

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

    ViewController.m中我添加了一个_draggedTile ivar,并设置在touchesBegan中,通过以下方法找到被触摸的瓷砖:

    - (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: 方法,但有时触摸不会完全在拖动的瓷砖上,并且运动不稳定或被取消)。

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多