How to hide / show UIimageview?

- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; CGRect viewRect = CGRectMake(250, 100, 30, 30); as = [[UIImageView alloc] initWithFrame:viewRect]; as.backgroundColor=[UIColor clearColor]; UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"check" ofType:@"png"]]; [as setImage:img]; [self.view addSubview:as]; BOOL test= [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"]; NSLog(@"%@", (test ? @"YES" : @"NO")); if(test == YES) { as.hidden=NO; } else { as.hidden=YES; } } 

The results are test YES , but imageView does not execute the .hidden command or is updated every time viewDidAppear . If it is not when I restart the application, and it disappears after I turn it on, yes, I show it perfectly, but after I never go around always, I can not hide it. any idea why it doesn't respond?

+6
source share
1 answer

The problem is that you create a new UIImageView every time your view appears. You must create a UIImageView as once:

 - (void)loadView { [super loadView]; CGRect viewRect = CGRectMake(250, 100, 30, 30); as = [[UIImageView alloc] initWithFrame:viewRect]; as.backgroundColor = [UIColor clearColor]; UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"check" ofType:@"png"]]; as.image = img; [self.view addSubview:as]; [as release]; } 

and then show / hide it - viewDidAppear method:

 - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; BOOL test = [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"]; NSLog(@"%@", (test ? @"YES" : @"NO")); if(test == YES) { as.hidden = NO; } else { as.hidden = YES; } } 
+11
source

Source: https://habr.com/ru/post/895854/


All Articles