0xS*_*ina 4 cocoa-touch objective-c uiview ios
我在屏幕上有一堆UIViews.我想知道什么是最好的方法来检查特定视图(我参考)是否与任何其他视图相交.我现在正在做的方法是,迭代所有子视图,并逐一检查框架之间是否有交叉点.
这看起来效率不高.有一个更好的方法吗?
Mik*_*yev 35
有一个名为CGRectIntersectsRect的函数,它接收两个CGRect作为参数,如果两个给定的rects相交,则返回.UIView有子视图属性,它是UIView对象的NSArray.所以你可以编写一个BOOL返回值的方法,它将遍历这个数组并检查两个矩形是否相交,如下所示:
- (BOOL)viewIntersectsWithAnotherView:(UIView*)selectedView {
NSArray *subViewsInView = [self.view subviews];// I assume self is a subclass
// of UIViewController but the view can be
//any UIView that'd act as a container
//for all other views.
for(UIView *theView in subViewsInView) {
if (![selectedView isEqual:theView])
if(CGRectIntersectsRect(selectedView.frame, theView.frame))
return YES;
}
return NO;
}
Run Code Online (Sandbox Code Playgroud)
首先,创建一些数组来存储所有 UIView 的框架及其关联的引用。
然后,您可以在后台线程中使用数组中的内容运行一些碰撞测试。对于仅针对矩形的一些简单碰撞测试,请查看这个问题:Simple Collision Algorithm for Rectangles
希望有帮助!
| 归档时间: |
|
| 查看次数: |
12435 次 |
| 最近记录: |