I am using multiple view controllers and trying the link the UITextfield in one view controller to the label in another view controller using delegate.
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate>
{
IBOutlet UITextField *txtField;
}
@end
ViewController.m
#import "ViewController.h"
#import "ViewController2nd.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
lbl.text = [NSString stringWithFormat:@"Hello, %@",txtField.text]
[txtField resignFirstResponder];
return YES;
}
@end
ViewController2nd.h
#import <UIKit/UIKit.h>
@interface ViewController2nd : UIViewController <UITextFieldDelegate> {
IBOutlet UILabel *lbl;
}
@end
ViewController2nd.m
#import "ViewController2nd.h"
@interface ViewController2nd ()
@end
@implementation ViewController2nd
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
The error i get is:
Use of undeclared identifier lbl in Viewcontroller.m
Not sure how to solve this problem. Need some guidance.. Thanks...
You don't have scope/excess of
ViewController2nd
'sIBOutlet UILabel *lbl;
inViewController
for this you need custom delegates, aViewController
a delegate ofViewController2nd
and pass data back. Have a look at this post for more details.The declaration of
lbl
is done in the wrong class.Post theIBOutlet UILabel *lbl;
within the interface ofviewcontroller.h
incase if you want the use of variable from other class change the code to
ViewController.m
ViewController2nd.h
ViewController2nd.m
Error is correct
There is no element in ViewController as lbl :)
You have to use ViewController2nd object to access its instance properties
Here is a place to start for object oriented programming with Objective-C.
You can always use Singleton Class to pass data back and forth. For example the appDelegate class is the singleton class. You can use shared instance of that class to pass data back and forth.
Example:
Instead of only relying on appDelegate class, I would recommend you to make a custom singleton class and use shared instance of that class.
Hope this would help you clear some doubts
First you have to init object of
ViewController2nd
.And one more thing,
lbl
ofViewController2nd
must have to be@property
and@synthesize
. Without that, you can't accesslbl
.