我使用此代码在我的iOS
应用程序中通过标记找到正确的UIImageView
,并且它可以工作。
selectedView = ((UIImageView*)[self.view viewWithTag:x]);
其中x是NSInteger。
现在,我有一个和UIImageView
标签相同的UITextview
。
有没有一个方法只返回UIImageView
,或者只返回带有此标记的Textview
,而不返回所有Views
?
类似:
selectedImageView = ((UIImageView*)[... viewWithTag:x]);
selectedTextView = ((UITextView*)[... viewWithTag:x]);
您可以这样做:
- (id) viewWithTag:(NSUInteger) tag andClass:(Class) className
{
for(UIView* subview in [self.view subviews])
{
if([subview isKindOfClass:className] && subview.tag == tag)
{
return subview;
}
}
return nil;
}
否,您需要为每个视图使用不同的标记。
您可以随时编写一个简单的类别来执行您想要的操作。在您的情况下,以下内容可能会起作用。
@interface UIView (MultitagSupport)
- (NSArray *)viewsWithTag:(NSInteger)tag andClass:(Class)class;
@end
-
@implementation UIView (MultitagSupport)
- (NSArray *)viewsWithTag:(NSInteger)tag andClass:(Class)class
{
NSMutableArray* matches = [NSMutableArray array];
for (UIView* subview in self.subviews)
{
if (subview.tag == tag && [subview isKindOfClass:class])
{
[matches addObject:subview];
}
}
return [NSArray arrayWithArray:matches]; // return immutable copy for safety
}
@end
您可以尝试使用谓词过滤子视图:
NSArray *foundImageViews = [self.view.subviews filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:@"tag = %d && class = %@", 1,
[UIImageView class]]];
这将返回所有标记为"1"的UIImageView子视图