Blade
Blade

Reputation: 1437

How do I use If-Statements correctly?

I tried a few things myself, but couldnt really get the handle around it. I wanna do two things: First the user can press one of three buttons - They all link to the same ViewController, but when User Presses the first button three labels change accordingly in this second ViewController. And then the user can enter some data which will be displayed in the third view, also accordingly on which button was pressed in the first view. I tried it with IF Statements, e.g. (IF ViewController.button1waspressed == True) and it didnt really work. I also tried it with tags e.g. (Button1.tag = 1)

Could someone give me a short example on how this could work?

FirstViewController.m

  - (IBAction)switch:(id)sender;

{
SecondViewController *second =[[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];

SecondViewController.m

  - (void)viewDidLoad
 {
[super viewDidLoad];

if (sender == self.button1) {
    NSString *greeting = [[NSString alloc] initWithFormat:@"Randomtext"];
    self.label.text = greeting; 
}



}

The problem is obvious in this one, SecondViewController cant see the property from the first one. (And yes I imported the FirstViewController and vice versa)

Upvotes: 1

Views: 395

Answers (1)

Jimmy Theis
Jimmy Theis

Reputation: 448

Your buttons should all directly call IBActions (methods defined like so):

- (IBAction)doSomething:(id)sender;

Defining them as IBActions exposes them to be connected with the blue connection lines in interface builder. Once you've hooked them up and the method is being called, you can simply use an equality check on the sender parameter, which the calling button will automatically set as itself.

if (sender == self.myButton) {
    // do something
}

Here I'm assuming that you've got a property called myButton in your ViewController, which would be an IBOutlet:

@property (nonatomic, retain) IBoutlet UIButton *myButton;

This exposes that property to be connected with the blue connection lines in interface builder, so your ViewController will know exactly which button you're talking about when you say myButton.

Upvotes: 3

Related Questions