0

I have a series of UIImageViews which are created in IB. I want to show and hide these depending on some button presses. I currently have a method which says if 1 is pressed then hide 2,3,4 then if 2 is pressed then hide 1,3,4. This works but I am trying to improve my code for an update.

My background is actionscript so I'm not sure if what I am trying to do is the right thing.

I basically want to evaluate a string reference to UIImageView, in AS I would use eval(string).

The method I am using is to create a string from a string and a number, so I get "image1". All works, but then I need to evaluate this into a UIImageView so I can update the alpha value.

Firstly is this possible and if not how should I be doing this? I'm starting to think that having this set up in interface builder maybe isn't helping?

user157733
  • 569
  • 2
  • 12
  • 26

1 Answers1

0

That's probably not a good way to work. What you want is an array of imageViews. Then you just need a numeric index, and you can go through the array of imageViews hiding everything that doesn't have the chosen index.

But how do you get an array of imageViews? See How to make IBOutlets out of an array of objects? It explains how to use IBOutletCollection.

If you have a separate button for each view, put those into an IBOutletCollection too. That way you can have something like this:

- (IBAction) imageButtonPressed:(id) sender;
{
    // The sender is the button that was just pressed.
    NSUInteger chosenIndex = [[self imageButtons] objectAtIndex:sender];
    for (NSUInteger imageIndex = 0; imageIndex < [[self imageViews] count]; imageIndex++)
    {
        // Hide all views other than the one associated with the pressed button.
        if (imageIndex != chosenIndex)
        {
            [[[self imageViews] objectAtIndex:imageIndex] setHidden:YES];
        }
        else
        {
            [[[self imageViews] objectAtIndex:imageIndex] setHidden:NO];
        }
    }
}

If you really, really need to associate the string image1 with an imageView, you can construct an NSDictionary associating your controls with unique string identifiers for later lookup. NSDictionary is powerful, but I'm drawing a blank on reasons why this would be needed.

NSMutableDictionary *viewLookup;
[viewLookup setObject:[[self imageViews] objectAtIndex:0] forKey:@"image0"];
[viewLookup setObject:[[self imageViews] objectAtIndex:1] forKey:@"image1"];
[viewLookup setObject:[[self imageViews] objectAtIndex:2] forKey:@"image2"];

[viewLookup setObject:[[self imageButtons] objectAtIndex:0] forKey:@"button0"];
// ...
// Can now look up views by name.
// ...
NSString *viewName = @"image1";
UIView *viewFound = [viewLookup objectForKey:viewName];
[viewFound doSomething];
Community
  • 1
  • 1
Cowirrie
  • 7,218
  • 1
  • 29
  • 42