3

This is mainly a delegation question because I'm still learning and don't get it. I don't know how to go about creating the delegate I need.

I know similar questions have been asked but the solutions don't help me out. How can I switch the text of a label on View 1 with the contents of a UITextField from View 2?

Thanks!

sbjluke
  • 309
  • 5
  • 15

1 Answers1

3

In this code snippet, ChildViewController is your View2 and ParentViewController is your View1.

In your ChildViewController.h file:

@protocol ChildViewControllerDelegate <NSObject>
- (void)parentMethodThatChildCanCall:(NSString *)string;  //pass back the string value from your textfield
@end

@interface ChildViewController : UIViewController 
{
    @property (weak, nonatomic) IBOutlet UITextField *myTextField;
}
@property (assign) id <ChildViewControllerDelegate> delegate;

In your ChildViewController.m file:

@implementation ChildViewController
@synthesize delegate;

// Some where in your ChildViewController.m file
// to call parent method:
//  [self.delegate parentMethodThatChildCanCall:myTextField.text];

In ParentViewController.h file:

@interface parentViewController <ChildViewControllerDelegate>
{
    @property (strong, nonatomic) IBOutlet UILabel *myLabel;
}

In ParentViewController.m file:

//after create instant of your ChildViewController

childViewController.delegate = self;

- (void) parentMethodThatChildCanCall:(NSString *)string
{
  // assign your passed back textfield value to your label here
    myLabel.text = string;
}
user523234
  • 14,323
  • 10
  • 62
  • 102