【问题标题】:Complex For & If loop confusion, returning and accessing classes. Objective-C复杂的 For & If 循环混淆、返回和访问类。 Objective-C
【发布时间】:2011-06-02 14:36:25
【问题描述】:

我有一个包含多个子视图的视图。我需要找到具有特定 UIImage 的特定 UIImageView。

这是我用来循环的代码:

BOOL fileExistsAtLocation;
for (id subview in drawGallery.subviews){
    if ([[subview class] isSubclassOfClass: [UIImageView class]]){
        // I need to detect the subview's image property to see if it matches.
    }
}

我试过了

if(subview.image == [UIImage imageNamed:image]){

}

但我被告知图像不是结构的一部分,这是可以理解的,因为所有子视图本质上都是 UIView 类型。如何仅定位 UIImageViews 然后检查它们的图像属性?

关于“标签”的答案,我尝试的代码是:

BOOL fileIsAtLocation;
for (id subview in drawGallery.subviews){
    if ([subview isKindOfClass:[UIImageView class]]){
        if ((UIView *)subview.tag){
            NSLog(@"FOUND");
        }
    }
}

【问题讨论】:

    标签: objective-c class uiimageview for-loop


    【解决方案1】:

    [UIImage imageNamed:image] 将返回该图像的新实例,因此它永远不会相等。我建议标记你所有的子视图。因此,当您创建图像视图时,请分配一个唯一标签(这可能只是一个自动递增的数字)。然后就可以根据标签来检测感兴趣的了。

    BOOL fileExistsAtLocation;
    for (id subview in drawGallery.subviews){
        if ([subView isKindOfClass:[UIImageView class]){
            // I need to detect the subview's image property to see if it matches.
            if([(UIView *)subView tag] == uniqueIDAssignedToImage) {
                // You have found your view   
            }
        }
    }
    

    还可以使用 isKindOfClass 检查类类型。

    希望这会有所帮助。

    【讨论】:

    • 实际上,UIImage 缓存。但是,是的,仍然不能保证指针相等。
    • 我有这个for (id subview in drawGallery.subviews){ if ([subview isKindOfClass:[UIImageView class]]){ NSLog(@"%d", (UIView *)subview.tag);,它给了我同样的错误——对成员标签的请求不是结构或联合等等。感谢您的建议
    • 总之,措辞很糟糕。但你是对的,你无法保证缓存何时刷新/恢复修改指针。
    • 试试[(UIView *)subview tag]
    • 它不允许我针对任何对象的任何属性。 UIImageView、UIView 或 NSObject。
    【解决方案2】:

    你尝试过使用类型转换吗?

    if(((UIImageView *)subview).image == [UIImage imageNamed:image]){
    
    }
    

    更新:

    • 你也可以尝试改变迭代逻辑:

      for (UIView *subview in drawGallery.subviews) {

    • 如果你必须找到带有标签的单个视图,请尝试

      UIImageView *imageViewISearchFor = [drawGallery viewWithTag:uniqueIDAssignedToImage];

    【讨论】:

    • 它只是说“在不是结构或联合的东西中请求成员'图像'”
    • 因为 is 必须是 if(((UIImageView *)subview).image == [UIImage imageNamed:image]){ (转换周围的附加大括号)。但是,给子视图分配标签,然后使用viewWithTag:找到它们,速度很快。
    猜你喜欢
    • 2018-09-08
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 2016-06-16
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多