Search code examples
iosobjective-cxcodeuiimageview

Change UIImageView's Images Using For Loop


I have been trying to code something that has a for loop from 0 through 3 that changes 3 different UIImageView's using their row number.

The first one would be called "c1", the second would be called "c2", the third "c3" etc..

These UIImageView's have already been defined in my .h file as well as accessible in my .m file. I have previously simply called it by the variable, but I need to iterate through the for loop to make the process more smooth instead of hardcoding a bunch of lines.

Current code:

 for (int i = 0; i < 3; i++){ 


                NSString *id = [NSString stringWithFormat:@"c%i" , i];


                UIImageView *imageViewInLoop = id;

                [self.imageViewInLoop setImage:[UIImage imageNamed:@"defaultphoto.jpg"]];

            }

No errors come up with this code besides a warning on the third line about initializing a UIImageView with a string. The code executes but the image does not change and nothing is printed to console. Please note before replying that the image and variable are correct as I have successfully manually done it before.


Solution

  • To access to properties by their names, use KeyValueCoding to get imageView by property name use valueForKey: method do:

         for(int i = 0; i < 3; i++){ 
    
             NSString *id = [NSString stringWithFormat:@"c%i" , i];
    
             UIImageView *imageViewInLoop = [self valueForKey:id];
    
             [imageViewInLoop setImage:[UIImage imageNamed:@"defaultphoto.jpg"]];
    
         }