views:

37

answers:

1

I have a UIButton in my MainWindow.xib

When I tap the button, I want to swap the view. How do I do that?

I also want to transfer some data between the views (such as color preference and a string)

ANy sample code OR links to where I can find my answer would be very helpful.

+1  A: 

alloc a temporary view controller, and call initWithNibName:. Then call [self presentModalViewController:(the view controller you just made) animated:YES]; (or NO). To pass data, create a method on your other view controller, add it to its .h file, and then in your .m file for the first view controller, import it and make it a class, and call [theviewcontrollermadeearlier yourmethod:argument :argument etc.]; e.g.:

MyFirstViewController.h:

#import <UIKit/UIKit.h>
#import "MySecondViewController.h"
...
@class MySecondViewController
...

MyFirstViewController.m:

...
MySecondViewController *tempVC = [[MySecondViewController alloc] initWithNibName:@"MySecondView"];
[self presentModalViewController:tempVC animated:YES];
[tempVC passDataWithString:@"a string" andColor:yellowcolor];

MySecondViewController.h:

@interface MySecondViewController : UIViewController {
...
}
- (void)passDataWithString:(NSString *)passedString andColor:(UIColor *)passedColor;

MySecondViewController.m:

...
- (void)passDataWithString:(NSString *)passedString andColor:(UIColor *)passedColor {
// Do something
}

EDIT: To make the button trigger this, in your first view controller's header file, add IBOutlet IBAction *buttonPressed; in the @interface section, and then between } and @end add - (IBAction)buttonPressed;
Go into Interface Builder, and connect the IBAction to the button.
Then, in your first view controller's main file, add this:

- (IBAction)buttonPressed {
    // The code to execute when pressed
}
jrtc27