2011-08-25 124 views
6
- (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; 
     } 
} 

test結果YESimageView不聽指揮.hidden或更新每次當viewDidAppear。如果它不是,當我重新啓動應用程序,它消失,我把它變成是我展現完美,但經過後比我永遠不會總是在那裏我不能讓它隱藏。 任何想法,爲什麼它沒有反應?如何隱藏/顯示UIimageview?

回答

11

問題是您每次出現視圖時都會創建新的UIImageView。你必須創建UIImageView因爲一旦:

- (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]; 
} 

,然後顯示/隱藏它 - viewDidAppear方法:

- (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; 
    } 
}