【发布时间】:2011-10-06 07:00:19
【问题描述】:
我有一个大的UIView 和许多小的subviews。我需要找到一个区域内的所有subviews。我目前正在遍历subviews 并使用CGRectContainsPoint。这可行,但 90% 的子视图通常不在我感兴趣的矩形内。
有没有更有效的方法来查找矩形内的所有subviews?
谢谢
【问题讨论】:
-
:你需要统计你的子视图吗?
我有一个大的UIView 和许多小的subviews。我需要找到一个区域内的所有subviews。我目前正在遍历subviews 并使用CGRectContainsPoint。这可行,但 90% 的子视图通常不在我感兴趣的矩形内。
有没有更有效的方法来查找矩形内的所有subviews?
谢谢
【问题讨论】:
CGRectContainsRect 会更合适。您仍然需要根据您对它们位置的假设来遍历可能在您的矩形中的所有子视图,但CGRectContainsRect 仍然比CGRectContainsPoint 更有意义。
CGRect area = CGRectMake(10,10,200,200);
NSMutableArray *viewsWithinArea = [[NSMutableArray alloc] init];
for (UIView *aView in [self.view subviews]) {
if(CGRectContainsRect(area,aView.frame)) [views addObject:aView];
}
【讨论】:
@james_womack 在 Swift 中的回答:
func subviewsWithin(area: CGRect) -> [UIView] {
return subviews.filter { area.contains($0.frame) }
}
【讨论】: