Search code examples
objective-cios5uiviewcontrolleruibuttonxcode-storyboard

UIButton removeFromSuperview


I went through guide from Apple "Your first iOS app"

and now I have a button, which is not declared in ViewController:

@interface HelloWorldViewController : UIViewController <UITextFieldDelegate>
- (IBAction)changeGreeting:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (copy, nonatomic) NSString *userName;
@end

Now i can remove label (and textField), using [label removeFromSuperview]; but i dont understand how to do it with button. Can someone help?


Solution

  • You should add an IBOutlet to the button as you did for the textfield and the label:

    @property (weak, nonatomic) IBOutlet UITextField *textField;
    @property (weak, nonatomic) IBOutlet UILabel *label;
    @property (weak, nonatomic) IBOutlet UIButton *button; // Don't forget to link to this from Interface Builder
    // ...
    

    Then you can remove the button using:

    [button removeFromSuperview];
    

    Also note that the tutorial you linked to says:

    The sender parameter in the action method refers to the object that is sending the action message (in this tutorial, the sender is the button).

    So if you want to remove the button when it is tapped (inside changeGreeting:), then you don't need the IBOutlet because you already have a reference to the button in the sender parameter:

    - (IBAction)changeGreeting:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        // ...
        [button removeFromSuperview];
        // ...
    }