按标签查找iOS UIImageview和UITextview

时间:2013-12-11 16:11:43

标签: ios uiimageview uitextview

我使用此代码在我的UIImageView应用中找到正确的iOS标签,但它确实有效。

selectedView = ((UIImageView*)[self.view viewWithTag:x]);

其中x是NSInteger。

现在,我的UITextview标记为UIImageView

是否有方法仅返回UIImageView或仅返回带有此标记的Textview而不是Views的所有内容?

像:

selectedImageView = ((UIImageView*)[... viewWithTag:x]);

selectedTextView = ((UITextView*)[... viewWithTag:x]);

4 个答案:

答案 0 :(得分:0)

不,您需要为每个视图使用不同的标记。

答案 1 :(得分:0)

你可以这样做:

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

答案 2 :(得分:0)

您始终可以编写一个简单的类别来执行您想要的操作。在您的情况下,以下内容可能会起作用。

@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

答案 3 :(得分:0)

您可以尝试使用谓词过滤子视图:

    NSArray *foundImageViews = [self.view.subviews filteredArrayUsingPredicate:
      [NSPredicate predicateWithFormat:@"tag = %d && class = %@", 1, 
      [UIImageView class]]];

这将返回标记为“1”的所有UIImageView子视图