Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove a programmatically added UIImageView

i'm making a program that has 2 Buttons in main view ;

one is called show and other one is hide,

when user presses show butoon an imageview gets added to screen

code :

-(IBAction)show{
  UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 155, 155)];
  img.image = [UIImage imageNamed:@"icon.png"];
  [self.view addSubview:img];
}

and when user presses the hide button , i want app to hide the image that has been just added (img)

but...

when i use

-(IBAction)add{
  [img removeFromSuperView];
}

Xcode says "img Undecleared"

edit : Some said define the object as a public object (@property) but problem is that the imageview gets added just once. but i wanted it to add new imageview every time user presses the Show button,

so i used the [[self subviews]objectAtIndex:xx]removeFromSuperview] method to solve the problem

like image 801
user1846654 Avatar asked Dec 27 '22 13:12

user1846654


2 Answers

Set a tag for your image view & then you can get it by this tag.

[img setTag:123];

...

[[self.view viewWithTag:123] removeFromSuperview];
like image 107
Kjuly Avatar answered Jan 12 '23 21:01

Kjuly


Create object of UIImageView in .h file like bellow..

UIImageView *img;

and in .m file viewDidLoad: method just add it like bellow..

- (void)viewDidLoad
{
    ///your another code
    img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 155, 155)];
    img.image = [UIImage imageNamed:@"icon.png"];
    img.hidden = YES;
    [self.view addSubview:img];
}

and when show button press show the image

-(IBAction)show{
    img.hidden = NO;
    [self.view bringSubviewToFront:img];
}

and for hide just hide like bellow..

-(IBAction)add{
    img.hidden = YES;
}
like image 23
Paras Joshi Avatar answered Jan 12 '23 22:01

Paras Joshi