Find subviews within rectangle
I have a large UIView
with many small subviews
. I need to find all subviews
within an area. I am currently iterating through subviews
and using CGRectContainsPoint
. This works, but 90% of the subviews are usually not within my rectangle of interest.
Is there a more efficient way to find all subviews
within a rect开发者_如何学Goangle?
Thanks
CGRectContainsRect
would be more appropriate. You'd still need to loop through all subviews that might be in your rect based on what you can assume about their positions, but CGRectContainsRect
still makes more sense than 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's answer in Swift:
func subviewsWithin(area: CGRect) -> [UIView] {
return subviews.filter { area.contains($0.frame) }
}
精彩评论