Question

My viewWillAppear method call "-(void)doSomething".

- (void)doSomething
{
    Y4AppDelegate * delegate = (Y4AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(delegate.booSomeValue == 0) {
        UIButton * aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [aButton setFrame:CGRectMake(20,360,280,40)];
        [aButton setTitle:@"Title"
                 forState:UIControlStateNormal];
        [aButton addTarget:self
                    action:@selector(mySelector)
          forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:aButton];
    }
}

It work, but aButton is still visible. What can I do to hide aButton? I have three UIViewController. In third i set delegate.booSomeValue to true. When I come back to previous UIViewController, I call this viewWillAppear but aButton is visible. I want to hide it.

Was it helpful?

Solution

The problem is that you added it once, and when you go back to it, you are not adding a second one, but the first one you added is still there, so you have to remove it.

To do so, you will need first to create a property to store the button, and check if it exists

if ( ... show button condition ... ) {

    if (!aButton) {
        ... create and show button ...
    }
}
else {
    if (aButton) {
         [aButton removeFromSuperview];
         aButton = nil;
    }
}

OTHER TIPS

Move this code to viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad]
    UIButton * aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    aButton.tag = 101;
    [aButton setFrame:CGRectMake(20,360,280,40)];
    [aButton setTitle:@"Title"
             forState:UIControlStateNormal];
    [aButton addTarget:self
                action:@selector(mySelector)
      forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:aButton];
}

And

- (void)doSomething
{
    Y4AppDelegate * delegate = (Y4AppDelegate *)[[UIApplication sharedApplication] delegate];
    UIButton * aButton =  (UIButton*)[self.view viewWithTag:101]; 
    aButton.hidden = delegate.booSomeValue;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top