So I'm trying to get a hang of using delegates, and I've watched a few tutorials on how to use them so far. I still find them confusing and after trying to implement one myself, have an issue that I can't seem to solve.
I have two ViewControllers, the first one ViewController
contains a UITextField *sampleTextField
and a button with the method switchViews
. It also contains the protocol declaration with the method sendTextToViewController
. SwitchViews
is also linked to a segue that switches to the SecondViewController
. In SecondViewController
the only object is a UILabel *outputLabel
When the user taps the button, it calls switchViews
and the view changes to SecondViewController, and upon loading outputLabel
should be changed to whatever text was entered in sampleTextField
in ViewController
. However the delegate method sendTextToViewController
is never being called. All objects are created in Interface Builder.
Here is the code to make it a bit easier to understand:
ViewController.h
#import <UIKit/UIKit.h>
@protocol TextDelegate <NSObject>
-(void)sendTextToViewController:(NSString *)stringText;
@end
@interface ViewController : UIViewController
- (IBAction)switchViews:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *sampleTextField;
@property (weak, nonatomic) id<TextDelegate>delegate;
@end
Then declared this in ViewController.m
- (IBAction)switchViews:(id)sender {
NSLog(@"%@", self.sampleTextField.text);
[self.delegate sendTextToViewController:self.sampleTextField.text];
}
SecondViewController.h
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface SecondViewController : UIViewController <TextDelegate>
@property (weak, nonatomic) IBOutlet UILabel *outputLabel;
@end
SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
@synthesize outputLabel;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
ViewController *vc = [[ViewController alloc]init];
[vc setDelegate:self];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)sendTextToViewController:(NSString *)stringText
{
NSLog(@"Sent text to vc");
[outputLabel setText:stringText];
}
I've looked at this and the first answer makes sense, but for some reason it's not working.
I do think that the problem is where I am setting calling [vc setDelegate:self]
, but not sure how to fix this. Some pointers in the right direction would be greatly appreciated. Keep in mind I'm new to obj-c so if you can explain what you are saying, that would be great. Thank you.