Question

My idea is to add generated integer value to the name of UIImageView. Here is an example: I have three UIImageViews named imageView1, imageView2, imageView3. When a button is pressed I have there this simple code: self.value = value + 1; (and of course I have this "value" declared) Now I want add some code which says something like: UIImage *img = [UIImage imageNamed:@"image.png"]; [imageView(value) setImage:img]; So this I want this part of code ...[imageView(value)... to use the value I defined above. How could I do this?

Was it helpful?

Solution

You can set a tag for your image views:

// set tag
[imageView1 setTag:1];
[imageView2 setTag:2];
//...

// get the image view with the tag
[(UIImageView *)[self.view viewWithTag:value] setImage:img];
//...

OTHER TIPS

You could use a tag, or you can put the UIImageViews into an NSArray. Then you can do something like

[((UIImageView *)[imageViewArray objectAtIndex:self.value]) setImage:img];

Here I tried to did according to your requirement.

my ViewController Class

- (void)viewDidLoad
{   
[super viewDidLoad];
ExtendedUIImageView *eimage=[[ExtendedUIImageView alloc]initExtendedUIImageViewWithFrame:CGRectMake(0, 0, 768, 1024)];
UIImage *img1=[UIImage imageNamed:@"mac.png"];
UIImage *img2=[UIImage imageNamed:@"images.jpeg"];
UIImage *img3=[UIImage imageNamed:@"mac.png"];
[eimage addUIImage:img1 ToExtendedImageViewWithRect:CGRectMake(100, 100, 100, 100) withTag:1];
[eimage addUIImage:img2 ToExtendedImageViewWithRect:CGRectMake(210, 100, 100, 100) withTag:2];
[eimage addUIImage:img3 ToExtendedImageViewWithRect:CGRectMake(320, 100, 100, 100) withTag:3];
[self.view addSubview:eimage];


}

- (IBAction)chageImage:(UIButton *)sender {
    NSLog(@"#####");
     UIImage *img2=[UIImage imageNamed:@"images.jpeg"];
    [eimage replaceImage:img2 forTag:3];
}

I Extended the UIView Class and created new Class ExtendedImageView class

ExtendedImageView.h

@interface ExtendedUIImageView : UIView
-(id)initExtendedUIImageViewWithFrame:(CGRect)rect;
-(void)addUIImage:(UIImage *)img ToExtendedImageViewWithRect:(CGRect)rect withTag:(int)n;
-(void)replaceImage:(UIImage *)newImg forTag:(int)n;    
@end

ExtendedImageView.m

@implementation ExtendedUIImageView
-(id)initExtendedUIImageViewWithFrame:(CGRect)rect{
    if([super initWithFrame:rect]){
        return  self;
    }
    return nil;
}

-(void)addUIImage:(UIImage *)img ToExtendedImageViewWithRect:(CGRect)rect withTag:(int)n{
    UIImageView *imgView=[[UIImageView alloc]initWithImage:img];
    //[imgView setBackgroundColor:[UIColor grayColor]];
    imgView.frame=rect;
    [imgView setTag:n];
    [self addSubview:imgView];

}

-(void)replaceImage:(UIImage *)newImg forTag:(int)n{
    for(UIView * img in [self subviews]){
        if([img isKindOfClass:[UIImageView class]]&&[img tag]==n){
            ((UIImageView *)img).image=newImg;
        }
    }
}
@end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top