bdkhsn bdkhsn - 2 months ago 14
iOS Question

how to change uiimageview image's programmatically

In my ios application i create uiimageviews programmatically like that,

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

productID=[products objectAtIndex:i];

UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(column*197+38 , row*350+8, 159, 45)];
//[button setImage:redButtonImage forState:UIControlStateNormal];
[button addTarget:self
action:@selector(buttonAction:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = productID;
[scrollView addSubview:button];



UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(column*197+170, row*350+25, 13, 13)];
imageView.tag=productID;
UIImage *image = [UIImage imageNamed:@"redImage.png"];
[imageView setImage:image];
[scrollView addSubview:imageView];


}


in my buttonActon, i want to change that uiimageview's image to another image. But i can not do that. Can anyone help me? Thank You.

Answer

try like this ,

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

                                   productID=[products objectAtIndex:i];

                                   UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                                   [button setFrame:CGRectMake(column*197+38 , row*350+8, 159, 45)];
                                   //[button setImage:redButtonImage forState:UIControlStateNormal];
                                   [button addTarget:self
                                              action:@selector(buttonAction:)
                                    forControlEvents:UIControlEventTouchUpInside];
                                   button.tag = 100+productID;
                                   [scrollView addSubview:button];



                                   UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(column*197+170, row*350+25, 13, 13)];
                                   imageView.tag=productID;
                                   UIImage *image = [UIImage imageNamed:@"redImage.png"];
                                   [imageView setImage:image];
                                   [scrollView addSubview:imageView];


                               }

keep this one in button action method and pass the imageview tag in the place of imgview.tag

     UIImageView *img=(UIImageView *)[scrollView viewWithTag:imgview.tag];
    img.image=[UIImage imageNamed:@"name.png"];
Comments