如何检测拖动到那里的子视图中的触摸

如何检测拖动到那里的子视图中的触摸

本文介绍了如何检测拖动到那里的子视图中的触摸(或者最快的方法来获取哪个子视图在其父视图的轻击下面)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超级视图,并且有很多子视图。我希望用户能够在超级视图内拖动手指,并且当他们在子视图上拖动时,该子视图会发生变化。

I've got a Super View, and its got a bunch of subviews. I'd like a user to be able to drag their finger inside the super view and when they drag over the subviews, that subview changes.

我需要这个非常

到目前为止,我尝试过的是在超级视图中,我可以从touchesBegan:withEvent:和touchesMoved获取触摸事件。 :withEvent:这两个结合在一起给了我所有我需要的触感。在每次调用这些方法时,我都必须遍历所有子视图并进行测试,例如

So far what i've tried, is in the super view I can get the touch events from touchesBegan:withEvent: and touchesMoved:withEvent: These two combined give me all the touches I need. On each call of these methods, I have to iterate through all of the subviews and test like so

for (UIView *view in self.subviews) {
    if (CGRectContainsPoint(view.frame, touchPoint) {
        return view;
    }
}

然后更改我想要的视图,问题是,从我的基准测试来看,这个过程只有两个很慢。

Then change that view however I want to. Problem is, from my benchmarking this process is just two slow.

我立即想到的是让子视图本身检测到触摸,然后在点击它们时发布通知或类似的东西,这样我就不必在每个奇特的触摸事件中都遍历超级视图中的所有对象。

My immediate thought is to have the subview's themselves detect the touch and then just post a notification or something like that when they are tapped. This way I don't have to iterate through them all inside the superview every freaking touch event.

我遇到的问题是,我还没有找到一种方法来获取子视图本身,以检测它们是否在被拖动时被触摸了。触摸实际上起源于另一个UIView。

The problem I am encountering with this, is that I haven't found a way to get the subviews themselves to detect that they are touched when they are just dragged over and the touch actually originated on a different UIView.

我愿意接受任何可以加快第一个过程的建议,

I'm open to any suggestions that either speed up the first process, or have a different way to accomplish this.

推荐答案

由于子视图位于网格上,并且如果它们的大小相等,则应该使用另一种方法来实现此目的。能够直接计算突出显示的一个。您只需要在创建时将它们的引用存储在2D数组中,出于性能考虑,建议您使用c数组。

Since your subviews are on a Grid and if they are equally sized, you should be able to calculate the highlighted one directly. You just need to store their references on creation in a 2D array, for performance I suggest to use a c-array.

int x = touchPoint.x/viewWidth;
int y = touchPoint.y/viewHeight;
return views[x][y];

根据您的版式,应考虑某些边框边距或视图之间的间距。

Depending on your Layout, some border margins or spacings between the views should be taken into account.

这样,您不需要迭代子视图数组,也不需要执行所有这些CGRectContainsPoint计算。

This way you do not need to iterate the subviews array and you do not need to perform all these CGRectContainsPoint calculations.

这篇关于如何检测拖动到那里的子视图中的触摸(或者最快的方法来获取哪个子视图在其父视图的轻击下面)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 16:12