开发者

Complex For & If loop confusion, returning and accessing classes. Objective-C

开发者 https://www.devze.com 2023-03-09 20:40 出处:网络
I have a view which has a number of subviews. I need to find a particular UIImageView with a particular UIImage.

I have a view which has a number of subviews. I need to find a particular UIImageView with a particular UIImage.

Here is the code I'm using to loop through:

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.
    }
}

I've tried

i开发者_如何转开发f(subview.image == [UIImage imageNamed:image]){

}

But I'm getting told that image isn't part of the structure, which is understandable as all the subviews are essentially of UIView type. How do I target only the UIImageViews and then check their image property?

Regarding the 'tag' answer, the code I tried was:

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


[UIImage imageNamed:image] will return a new instance of that image so it will NEVER be equal. I'd suggest tagging all of your subviews. So when you create the image views, assign a unique tag (this could just be an auto incrementing number). Then you can detect of interest based on the tag.

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

Also use isKindOfClass to check the class type.

Hope this helps.


Did you try to use type conversion?

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

}

UPDATE:

  • You can also try to change iteration logic:

    for (UIView *subview in drawGallery.subviews) {

  • If you have to find a single view with tag, try

    UIImageView *imageViewISearchFor = [drawGallery viewWithTag:uniqueIDAssignedToImage];

0

精彩评论

暂无评论...
验证码 换一张
取 消