0

我正在以编程方式生成几个 UIButton,然后使用块动画为它们设置动画。我可以通过实现此答案中的代码来确定触摸了哪个按钮(如下所示)。

我现在的问题是图像可以重叠,所以当在给定的触摸位置有超过 1 个视图时,我在 touchesBegan 中的代码会拉出错误的按钮(即,获取我正在触摸的可见按钮下方的图像)。

我想使用 [touch view] 与屏幕上的 UIButtons 进行比较:

if (myButton==[touch view]) { ...

但这种比较总是失败。

我的接触开始:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    for (UIButton *brain in activeBrains) {
        //Works, but only when buttons do not overlap
        if ([brain.layer.presentationLayer hitTest:touchLocation]) {
            [self brainExplodes:brain];
            break;
        }

        /* Comparison always fails
        if (brain == [touch view]) {
            [self brainExplodes:brain];
            break;
        }
        */
    }
}

所以我的问题是如何确定哪些重叠图像高于其他图像?

4

3 回答 3

1

我在这里的代码中做了一些假设,但基本上你需要获取所有已触摸按钮的列表,然后找到“顶部”的按钮。顶部的那个应该具有子视图数组中按钮的最高索引。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
    NSMutableArray *brainsTouched = [[NSMutableArray alloc] init];
    for (UIButton *brain in activeBrains) {
        //Works, but only when buttons do not overlap
        if ([brain.layer.presentationLayer hitTest:touchLocation]) {
            [brainsTouched addObject:brain];
        }
    }
    NSUInteger currentIndex;
    NSInteger viewDepth = -1;
    UIButton *brainOnTop;
    for (UIButton *brain in brainsTouched){
        currentIndex = [self.view.subviews indexOfObject:brain];
        if (viewDepth < currentIndex){ 
            brainOnTop = brain;
            viewDepth = currentIndex;
        }
    }
    [self brainExplodes:brainOnTop];
}

另外,我在编辑窗口中输入了这个,所以请原谅拼写错误。

于 2012-05-06T23:40:32.983 回答
0

UIView 类包含一个标记属性,您可以使用该属性标记具有整数值的单个视图对象。您可以使用标签来唯一标识视图层次结构中的视图,并在运行时执行对这些视图的搜索。(基于标签的搜索比自己迭代视图层次结构要快。)标签属性的默认值为 0。

要搜索标记视图,请使用 UIView 的 viewWithTag: 方法。该方法执行接收器及其子视图的深度优先搜索。它不搜索超级视图或视图层次结构的其他部分。因此,从层次结构的根视图调用此方法会搜索层次结构中的所有视图,但从特定子视图调用它只会搜索视图的子集。

于 2012-05-07T00:00:59.373 回答
0

感谢@Aaron 帮助您找到一个好的解决方案。我确实针对我的情况重构了您的答案,以获得不明显的性能增益(wee),但更重要的是,我认为,如果我将来必须重构,阅读量就会减少。

我想,回想起来很明显,但是 activeBrains 数组当然反映了子视图的顺序(因为每个新大脑都在添加到超级视图之后立即添加到数组中)。因此,通过简单地向后循环阵列,正确的大脑正在爆炸。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    for(int i=activeBrains.count-1; i>=0; i--) {
        UIButton *brain = [activeBrains objectAtIndex:i];

        if ([brain.layer.presentationLayer hitTest:touchLocation]) {
            [self explodeBrain:brain];
            break;
        }
    }
}
于 2012-05-08T16:34:51.613 回答