OGeek|极客世界-中国程序员成长平台

标题: ios - 在主视图中处理 touchesBegan - 如何获取被触摸的 subview ? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 09:06
标题: ios - 在主视图中处理 touchesBegan - 如何获取被触摸的 subview ?

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

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

所以我试图将 touchesBegan 和 friend 移动到主应用程序 View (参见 ViewController.m)。

我的问题是:

最初,我在 contentView 中有这段代码(参见 GameBoard.m ),以便在 scrollView 上启用 subview 拖动:

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

    return result == self ? nil : result;
}

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

app screenshot

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

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

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

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

我的问题是:

如何在新的touchesBegan方法中找到被触摸的tile?



Best Answer-推荐答案


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

ViewController.m我添加了一个 _draggedTile ivar 并在 touchesBegan 中设置了它,方法是使用以下方法查找触摸的瓷砖:

- (SmallTile*) findTileAtPointCGPoint)point withEventUIEvent*)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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4