屏幕上有许多UIView。我想知道检查特定视图(我已经引用)是否与任何其他视图相交的最佳方法是什么。我现在所做的方式是,遍历所有子视图并逐个检查框架之间是否存在交集。
这似乎不是很有效率。有更好的方法吗?
屏幕上有许多UIView。我想知道检查特定视图(我已经引用)是否与任何其他视图相交的最佳方法是什么。我现在所做的方式是,遍历所有子视图并逐个检查框架之间是否存在交集。
这似乎不是很有效率。有更好的方法吗?
有一个叫做CGRectIntersectsRect的函数,它接收两个CGRect作为参数,并返回这两个矩形是否相交。而UIView有一个子视图属性subviews,是一个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;
}
foreach
?一定是打错了吧?不过回答很棒,应该被采纳。+1 - katzenhutNSIntersectsRect
替代 CGRectIntersectsRect
。 - Stephan在我的情况下,视图是嵌套的,所以我做了这个(适用于嵌套和非嵌套):
extension UIView {
func overlaps(other view: UIView, in viewController: UIViewController) -> Bool {
let frame = self.convert(self.bounds, to: viewController.view)
let otherFrame = view.convert(view.bounds, to: viewController.view)
return frame.intersects(otherFrame)
}
}
func checkViewIsInterSecting(viewToCheck: UIView) -> Bool{
let allSubViews = self.view!.subviews //Creating an array of all the subviews present in the superview.
for viewS in allSubViews{ //Running the loop through the subviews array
if (!(viewToCheck .isEqual(viewS))){ //Checking the view is equal to view to check or not
if(CGRectIntersectsRect(viewToCheck.frame, viewS.frame)){ //Checking the view is intersecting with other or not
return true //If intersected then return true
}
}
}
return false //If not intersected then return false
}
let viewInterSected = self.checkViewIsInterSecting(newTwoPersonTable) //It will give the bool value as true/false. Now use this as per your need
谢谢。
希望这有所帮助。
CGRectIntersectsRect(viewToCheck.frame, viewS.frame)
替换为 viewToCheck.frame.intersects(viewS.frame)
。 - kabiroberai