开发者

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) }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜