Find subviews within rectangle

时间秒杀一切 提交于 2019-12-13 19:58:05

问题


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 rectangle?

Thanks


回答1:


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];
}



回答2:


@james_womack's answer in Swift:

func subviewsWithin(area: CGRect) -> [UIView] {
    return subviews.filter { area.contains($0.frame) }
}


来源:https://stackoverflow.com/questions/7671114/find-subviews-within-rectangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!