gpt4 book ai didi

iphone - 在 iOS 中检测拖动时的碰撞

转载 作者:行者123 更新时间:2023-11-29 11:06:55 25 4
gpt4 key购买 nike

给定可以拖动 View 的 View 层次结构,检测拖动 View 与其他 View 之间的碰撞的最有效方法是什么?

这将是蛮力方法(在伪代码中):

- (void) onDrag 
{
CGRect absoluteDraggedViewRect; // Calculate
for (UIView *otherView in hierarchy)
{
CGRect absoluteOtherViewRect; // Calculate
if (CGRectIntersectsRect(absoluteDraggedViewRect, absoluteOtherViewRect))
{
// Collision!
}
}
}

你会如何改进上面的代码?

最佳答案

我认为目前唯一“可见”的改进是添加:

if (otherView == self)
continue;

在你的循环中。当然,前提是 selfhierarchy 中。

最后,您必须检查每个 View 是否与您拖动的 View 相交。如果您后来意识到这是一个严重的性能问题,您可以尝试分散工作负载。您可以将“移动区域”分成多个部分。拖动 View 后,您可以计算它与哪些部分相交,并保存一个字典或其他适当的数据结构,其中包含每个部分中的所有 View 。然后你只需要循环遍历拖动 View 部分的 View 。但是,如果这样做有返回,则取决于您的具体用例。如果您当前的方法被证明是性能问题,我只会考虑它。

正如 Donald Knuth 曾经说过的:

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"

关于iphone - 在 iOS 中检测拖动时的碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com