Search code examples
iphoneuibuttoncore-animation

Xcode hide self created button


I created a button programmatically:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(290, 120, 40,20); // position in the parent view and set the size of the button
[myButton setTitle:@"Back" forState:UIControlStateNormal];
// add targets and actions
[myButton addTarget:self action:@selector(backLogin:) forControlEvents:UIControlEventTouchUpInside]; 
// add to a view
[myButton setAlpha:0];
[self.view addSubview:myButton];    

Now I would like to hide this button again using another method and use animation to make the button fade away (!). Obviously, I cannot use the variable myButton again and I don't want to make the variable global. Removing the Subview from the layer won't animate I guess. Do you have an idea? I can't make it to work... Thanks!


Solution

  • I don't think you're going about this the right way, but first of all, you're adding an invisible button to your view. Assuming you meant to add the button with an alpha of 1, here we go.

    Fist of all, set a tag for the button:

    myButton.tag = 1;
    

    Any will do, as long as you're not using that tag for something else.

    Next in your other method we can iterate through the subviews in your view controller and we can find the view with the tag of 1, and set it's alpha to 0 with a nice fade effect:

    for (UIButton *button in self.view.subviews) {
        if (button.tag == 1) {
            [UIView animateWithDuration:2.0 animations:^ {
                button.alpha = 0;
            }];
        }
    }
    

    However, this is really a bad way to go about it, and I would highly suggest just creating an instance variable.