首先,通过过滤,意味着在子视图中查找所有(targetClass)视图。
通常,如果我们想按类过滤子视图,我们可能会这样做:
// Create an array to hold them
NSMutableArray *filteredViews = [NSMutableArray new];
// enumerate and check
for (UIView *view in parentView.subviews) {
if ([view isMemberOfClass:[targetClass class]) {
[filteredViews addObject:view];
}
}
这是正确的方法吗?
Cocoa Touch有专门的方法来过滤子视图吗?
答案 0 :(得分:4)
您可以使用NSPredicate定义规则以选择所需的项目。注意我使用isKindOfClass
而不是isMemberOfClass
,因为前者考虑了类层次结构,并且能够识别您正在寻找的类的子类。
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"self isKindOfClass: %@", [targetClass class]];
NSArray* filteredViews= [parentView.subviews filteredArrayUsingPredicate:predicate];