سؤال

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?

هل كانت مفيدة؟

المحلول

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];
    // ...
}

نصائح أخرى

You need to declare the button in the controller like you did as an IBAction and this time declare this as an Outlet(IBoutlet).. this way you will get its reference in code..

Alternatively .. you can set a tag to the button in Interface Builder ..

and then retrieve in code using viewWithTag: method

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top