This question already has answers here:
Passing data between view controllers
(45 answers)
Access Variable from Another Class - Objective-C
(2 answers)
Closed 8 years ago.
I'm creating a project so that I have two view controllers, connected by a modal segue with an identifier "login_success".
In the primary view controller, I have a text field that takes the input of whatever the user types, and a button to perform the segue.
In the next controller, I have a label that is supposed to print out whatever the user typed.
My code:
DICViewController.h (First View Controller):
#import <UIKit/UIKit.h>
#interface DICViewController : UIViewController <UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextField *txtUsername;
- (IBAction)sigininClicked:(id)sender;
- (IBAction)backgroundTap:(id)sender;
#end
DICViewController.m:
#import "NewViewController.h"
#interface DICViewController ()
#end
#implementation DICViewController
- (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.
}
- (IBAction)sigininClicked:(id)sender {
{
[self performSegueWithIdentifier:#"login_success" sender:self];
}
}
- (IBAction)backgroundTap:(id)sender {
[self.view endEditing:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
#end
NewsViewController.h (The other view controller):
#import <UIKit/UIKit.h>
#interface NewViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *steamId; //my label
#end
NewsViewController.m:
No code was added here.
Thanks in advance to anyone that can help.
Again, I would like to be able to set the text in the label equal to the text the user types in the text field.
When performing a segue the preferred way to pass data from one view controller to another is to make use of the method -prepareForSegue:sender:.
In your case the following lines of code should work:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NewsViewController *newsVC = segue.destinationViewController;
[newsVC view]; // this loads the view so that its subviews (the label) are not nil
newsVC.steamID.text = self.txtUsername.text;
}
(Place this method anywhere in your DICViewController.m.)
I think The better way is to set global variables. Just make normal class
variables.h
#import <Foundation/Foundation.h>
#interface variables : NSObject {
float VariableYouWant;
}
+ (_tuVariables *)sharedInstance;
#property (nonatomic, assign, readwrite) float VariableYouWant;
and
variables.m
#import "variables.h"
#implementation variables
#synthesize VariableYouWant = _VariableYouWant;
+ (_tuVariables *)sharedInstance {
static dispatch_once_t onceToken;
static variables *instance = nil;
dispatch_once(&onceToken, ^{
instance = [[variables alloc] init];
});
return instance;
}
- (id)init {
self = [super init];
if (self) {
}
return self;
}
#end
Way to use:
import header file of variables and
variables *globals = [variables sharedInstance];
and simply access variables with
globals.VariableYouWant =
Related
I'm trying to use an xib file (which is just a simple view) on my viewcontroller more than once. I can add it on my viewcontroller more than once and interact with both of them. The question is, how can i distinguish between these views to know which one i'm clicking?
For example, when i tap on my firstview, i want to print "apples" and when i tap on second view i wan to print "oranges"
Below you can see my code and here is github repo for you to play with my code: https://github.com/TimurAykutYildirim/demoView/tree/multiple-instance
ViewController.h
#import <UIKit/UIKit.h>
#import "Mini.h"
#interface ViewController : UIViewController <SelectionProtocol>
#property (weak, nonatomic) IBOutlet Mini *miniView;
#property (weak, nonatomic) IBOutlet Mini *miniView2;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.miniView.delegate = self;
self.miniView2.delegate = self;
}
-(void) isClicked {
NSLog(#"apples");
NSString * storyboardName = #"Main";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:#"SecondViewController"];
[self presentViewController:vc animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Mini.h
#import <UIKit/UIKit.h>
#protocol SelectionProtocol;
#interface Mini : UIView
#property (nonatomic, weak) id<SelectionProtocol> delegate;
- (IBAction)btnClick:(id)sender;
#end
#protocol SelectionProtocol <NSObject>
#required
-(void) isClicked;
#end
Mini.m
#import "Mini.h"
#implementation Mini
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self load];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self load];
}
return self;
}
- (void)load {
UIView *view = [[[NSBundle bundleForClass:[self class]] loadNibNamed:#"Mini" owner:self options:nil] firstObject];
[self addSubview:view];
view.frame = self.bounds;
}
- (IBAction)btnClick:(id)sender {
if ([self.delegate conformsToProtocol:#protocol(SelectionProtocol)]) {
[self.delegate isClicked];
}
}
#end
There are lots of ways that you could do that. Here are two:
Add a sender parameter to your -[ViewController isClicked] method, and change Mini so that calls to -isClicked pass in a pointer to self. Then the code in -isClicked can compare that to each of the instances of Mini that it knows about, i.e. self.miniView and self.miniView2, to see if either of those is the one that sent the message.
Add a property to Mini that lets you distinguish between the two, e.g. name. You can configure that property in -viewDidLoad, like self.miniView.name = #"apples", or you can even do it in the .xib file using "user defined runtime attributes." Then you can have Mini pass it's name property as a parameter to methods that need to know which instance of Mini is the caller. (Or, combine 1 & 2 and pass a reference to self so that ViewController can examine the name parameter or anything else it wants.)
I'm assuming from your question that somewhere in the Mini xib there is an outlet with the text "apples" (or whichever fruit for that particular xib).
In that case, you can just change your protocol to:
- (void)isClickedFromView:(Mini *)mini
In the delegate (ViewController.m) change the btnClick action to:
- (IBAction)btnClick:(id)sender {
if ([self.delegate conformsToProtocol:#protocol(SelectionProtocol)]) {
[self.delegate isClickedFromView:self];
}
}
Add an outlet like fruitLabel to your Mini class.
#property (weak, nonatomic) IBOutlet UILabel *fruitLabel
Now when the delegate gets the call you can call:
NSLog(#"Fruit: %#", mini.fruitLabel.text);
===== Additional answer for if the data (in this case fruits) is available in code =====
If you have the data programmatically already (like an array of fruits), It might be easier to just put the Mini classes in an array ordered the same way.
So if miniViewArray contains an array of your Mini classes,
and fruitArray contains an array of NSStrings of fruits you can do:
At the time you set the miniView's delegate you can add them to the array..something like:
NSArray *fruitArray = #[ #"apples", #"oranges" ];
NSArray *miniViewArray = #[ miniView, miniView2 ];
Then in the delegate call you can do (Using the same protocol change as above):
- (void)isClickedFromView:(Mini *)mini {
NSInteger fruitIndex = [miniViewArray indexOfObject:mini];
NSString fruitName = fruitArray[fruitIndex];
NSLog(#"Fruit: %#", fruitName);
}
I use ENUM for distinguish between the view type.
typedef NS_ENUM(NSUInteger, <#MyViewType#>) {
<#MyViewTypeDefault#>,
<#MyViewTypeA#>,
<#MyViewTypeB#>,
};
#property (nonatomic, assign) MyEnum viewType;
Protocol:
-(void) isClickedForViewType:(MyEnum)viewType;
Common approach for calling delegate method is to include caller as a param. In your case it should be something like this:
- (IBAction)btnClick:(id)sender {
if ([self.delegate conformsToProtocol:#protocol(SelectionProtocol)]) {
[self.delegate isClickedOnMiniView:self];
}
}
Basically, this convention was created to cover such cases - one object is a delegate of many similar ones.
Check apple docs for examples of this convention:
https://developer.apple.com/documentation/uikit/uitableviewdelegate
I am trying yo pass data of two textfields in secondViewController to ViewController and set text of labels in ViewController.
But the delegate method for passing data is not being called. I have checked it by putting break point. Hence label text is not changing.
SecondViewController.h
#import <UIKit/UIKit.h>
#class SecondViewController;
#protocol SecondViewDelegate <NSObject>
-(void)getText1:(NSString*)str1 andText2:(NSString*)str2;
#end
#interface SecondViewController : UIViewController<UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextField *textField1;
#property (weak, nonatomic) IBOutlet UITextField *textField2;
#property (weak) id<SecondViewDelegate>delegate;
#end
SecondViewController.m
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
#synthesize delegate=_delegate;
- (void)viewDidLoad {
[super viewDidLoad];
self.textField1.delegate=self;
self.textField2.delegate=self;
[self.textField1 becomeFirstResponder];
// 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
{
if ( textField == self.textField1 ) { [self.textField1 resignFirstResponder]; [self.textField2 becomeFirstResponder]; }
else if ( textField == self.textField2) {
[_delegate getText1:self.textField1.text andText2:self.textField2.text];
NSLog(#"%#",self.textField1.text);
[self.navigationController popToRootViewControllerAnimated:YES];
}
return YES;
}
#end
View Controller.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface ViewController : UIViewController<SecondViewDelegate>
-(void)getText1:(NSString *)str1 andText2:(NSString *)str2;
#end
View Controller.m
#import "ViewController.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UILabel *label1;
#property (weak, nonatomic) IBOutlet UILabel *label2;
#end
#implementation ViewController
#synthesize label1;
#synthesize label2;
- (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.
}
- (IBAction)onClick:(id)sender {
SecondViewController* sv= [[SecondViewController alloc] init];
sv.delegate=self;
[self performSegueWithIdentifier:#"moveToSecondController" sender:self];
}
-(void)getText1:(NSString *)str1 andText2:(NSString *)str2{
[label1 setText:str1];
[label2 setText:str2];
}
#end
The problem is that you've created two SecondViewController objects and made your ViewController the delegate of the wrong one.
This: [[SecondViewController alloc] init] creates an object in code. This: [self performSegueWithIdentifier:#"moveToSecondController" sender:self] creates an object from a storyboard definition.
Don't bother creating the first one, just perform the segue. Then, implement the prepareForSegue method and set your delegate there, using the destination controller (which will be the correct SecondViewController).
Try setting your delegate in prepareForSegue method like:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:#"YOUR_SEGUE_NAME_HERE"])
{
// Get reference to the destination view controller
SecondViewController *vc = [segue destinationViewController];
vc.delegate=self;
}
}
You don't need to declare your delegate method in ViewController.h. It has already been done in SecondViewController.h as the delegate method.
import
import "SecondViewController.h"
#interface ViewController : UIViewController
// Remove this method in ViewController.h file this is call as a simple method for ViewController class
-(void)getText1:(NSString *)str1 andText2:(NSString *)str2;
#end
I'm having problems passing data between two view controllers.
I've seen two ways to do this.
One involves implementing prepareForSeque: in the segue's source view controller and another involves setting properties in the viewDidLoad: method of the segue's destination view controller.
e.g.-
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"toEmailReservationViewController"]) {
FLSendEmailViewController *controller = (FLSendEmailViewController *)segue.destinationViewController;
if (!controller.startDateField.text) {
controller.startDateField.text = #"today";
}
}
}
and
- (void)viewDidLoad
{
[super viewDidLoad];
self.startDateField.text = ((FLViewController *)self.presentingViewController).startDate;
}
I've got these to work on simple apps using two UIViewController. However, I can't get them to work on an app that has a UITabViewController connected to some UINavigationViewController connected to custom subclasses of UIViewController. When I click the button to perform the push seque, I get to the view I want, but the startDateField.text doesn't have the text from the segue's source view controller.
Why are these methods of sharing data not working with the tab controller and navigation controller setup?
I noticed that in prepareForSegue: I can't set controller.startDateField.text; as shown when I try to set it and use NSLog to display it. Could this be the problem? Is it possible that the property controller.startDateField.text doesn't exist yet?
I'm trying to grab the date from a datePicker in an instance of FLViewController, store this date in the property NSString *startDate, and in an instance of FLSendEmailViewController set NSString *startDateField.text to the `NSString *startDate'.
Here are the UIViewController subclasses I created:
FLViewController.h
#import <UIKit/UIKit.h>
#import "FLSendEmailViewController.h"
// import frameworks to use ad
#import AddressBook;
#import AddressBookUI;
#interface FLViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIScrollView *theScroller;
#property (weak, nonatomic) NSString *startDate;
#property (weak, nonatomic) NSString *stopDate;
- (IBAction)exitToReservations:(UIStoryboardSegue *)sender;
#end
FLViewController.m
#import "FLViewController.h"
#interface FLViewController ()
#property (weak, nonatomic) IBOutlet UIDatePicker *startReservationDatePicker;
#property (weak, nonatomic) IBOutlet UIDatePicker *stopReservationDatePicker;
#end
#implementation FLViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.theScroller setScrollEnabled:YES];
[self.theScroller setContentSize:CGSizeMake(280, 1000)];
//setup reservationDatePicker
[self.startReservationDatePicker addTarget:self
action:#selector(startDatePickerChanged:)
forControlEvents:UIControlEventValueChanged];
[self.stopReservationDatePicker addTarget:self
action:#selector(stopDatePickerChanged:)
forControlEvents:UIControlEventValueChanged];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// add method called when user changes start date
- (void)startDatePickerChanged:(UIDatePicker *)datePicker
{
NSDateFormatter *dateFortmatter = [[NSDateFormatter alloc] init];
[dateFortmatter setDateFormat:#"dd--MM-yyyy HH:mm"];
// get date using stringFromData: method and getter datePicker.date
self.startDate = [dateFortmatter stringFromDate:datePicker.date];
NSLog(#"The start date is %#", self.startDate);
}
// add method called when user changes stop date
- (void)stopDatePickerChanged:(UIDatePicker *)datePicker
{
NSDateFormatter *dateFortmatter = [[NSDateFormatter alloc] init];
[dateFortmatter setDateFormat:#"dd--MM-yyyy HH:mm"];
// get date using stringFromData: method and getter datePicker.date
self.stopDate= [dateFortmatter stringFromDate:datePicker.date];
NSLog(#"The stop date is %#", self.stopDate);
}
- (IBAction)exitToReservations:(UIStoryboardSegue *)sender {
// execute this code upon unwinding
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"toEmailReservationViewController"]) {
FLSendEmailViewController *controller = (FLSendEmailViewController *)segue.destinationViewController;
if (!controller.startDateField.text) {
controller.startDateField.text = #"today";
NSLog(#"in vc startDate is null but set to %#",controller.startDateField.text );
}
}
}
#end
FLSendEmailViewController.h
#import <UIKit/UIKit.h>
#class FLViewController;
#interface FLSendEmailViewController : UIViewController
#property (retain, nonatomic) IBOutlet UITextField *startDateField;
#property (retain, nonatomic) IBOutlet UITextField *stopDateField;
#end
FLSendEmailViewController.m
#import "FLSendEmailViewController.h"
#import "FLViewController.h"
#interface FLSendEmailViewController ()
- (IBAction)sendEmail:(id)sender;
#property (weak, nonatomic) IBOutlet UITextField *numberOfDoggies;
#property (weak, nonatomic) IBOutlet UITextField *emailAddressField;
- (IBAction)hideKeyboard:(id)sender;
#end
#implementation FLSendEmailViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.startDateField.text = ((FLViewController *)self.presentingViewController).startDate;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sendEmail:(id)sender {
NSString *emailString = [NSString stringWithFormat:#"I would like you to watch my %# doggies from %# to %#. Thank you.", self.numberOfDoggies.text, self.startDateField.text, self.stopDateField.text];
NSLog(#"%#",emailString);
}
- (IBAction)hideKeyboard:(id)sender {
[self.startDateField resignFirstResponder];
}
#end
Import the FLSendEmailViewController.h to the "InitialViewController.h"
Add this property to the FLSendEmailViewController.h
#property (nonatomic, strong) NSString *exportedData;
Add this to the FLSendEmailViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.startDateField.text = self.exportedData
}
4.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"toEmailReservationViewController"]) {
FLSendEmailViewController *controller = (FLSendEmailViewController *)segue.destinationViewController;
if (!controller.startDateField.text) {
controller.exportedData = #"today";
}
}
}
This "sharing method" works in any case when from a controller go to another controller.
So, in case of a navigation controller, if you want push another viewController passing the data, you have just to set the trigger in the Storyboard (if you are using storyboard) from the button, and the new viewController.
So, you will not met troubles. Otherwise, you are committing other type of errors, and in this case, update your question.
I'm trying to separate the UITextViewDelegate methods from the main class of my project, I created a class to manage the delegate methods, but I can not change the values of the IBOulets from the main class.
I made a test project with a ViewController and a TextFieldController, in the Storyboard I add a text field and a label. What I want to do is change the text of the label when I start to write in the text field. Here is the code:
ViewController.h:
#import <UIKit/UIKit.h>
#import "TextFieldController.h"
#interface ViewController : UIViewController
#property (strong, nonatomic) IBOutlet UITextField *textField;
#property (strong, nonatomic) IBOutlet UILabel *charactersLabel;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) TextFieldController *textFieldController;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_textFieldController = [[TextFieldController alloc] init];
_textField.delegate = _textFieldController;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
TextFieldController.h:
#import <UIKit/UIKit.h>
#import "ViewController.h"
#interface TextFieldController : UIViewController <UITextFieldDelegate>
#end
Text Field Controller.m:
#import "TextFieldController.h"
#interface TextFieldController ()
#property ViewController *viewController;
#end
#implementation TextFieldController
- (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.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
NSLog(#"hello");
_viewController.charactersLabel.text = #"hello";
return YES;
}
#end
When I start writing in the text field the message "Hello" is printed in the log, but the text of the label does not change. I want to know how to change the label text value from the other class.
First change the TextFieldController.h like this:
#import <UIKit/UIKit.h>
#import "ViewController.h"
#interface TextFieldController : NSObject <UITextFieldDelegate>
{
}
#property (nonatomic, assign) ViewController *viewController;
#end
Then change your TextFieldController.m file like this:
#import "TextFieldController.h"
#interface TextFieldController ()
#end
#implementation TextFieldController
- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
NSLog(#"hello");
self.viewController.charactersLabel.text = #"hello";
return YES;
}
#end
In the ViewController.m do like that:
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) TextFieldController *textFieldController;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_textFieldController = [[TextFieldController alloc] init];
_textFieldController.viewController = self;
_textField.delegate = _textFieldController;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
This will work but I personally dont like that way you took.
Good luck :)
It's failing because _viewController is nil. You need to assign the viewController property in your delegate in order to support the two way communication.
Also, I'd strongly recommend you make your delegate object a subclass of NSObject, and not UIViewController. It does nothing with controlling views. You can just manually instantiate it in your ViewController objects viewDidLoad.
In TextViewController I don't see where the viewController property (_viewController ivar) is being set so it is probably nil. You should set it when you create the TextViewController instance.
When you are navigating to other controllers using storyboad's segue then you need to implement prepareForSegue method to initialised its properties as follows
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"segue for textFieldController"])
{
TextFieldController *_textFieldController = [segue destinationViewController];
_textField.delegate = _textFieldController;
}
}
But I was wondering, why are you setting textFieldDelegate here, why can't you set in TextFieldController's viewDidLoad method as then you didn't you to implement above prepareForSegue method call?
Besides you are keeping strong reference of each other and you are creating strong retain cycle.
One more thing, following code
_textField.delegate = _textFieldController;
will not work, until textFieldController is loaded and its viewDidLoad method is being called as you are only initialising it but its outlets will not be connected until view is loaded into navigation stack.
Could anyone please help me in the following problem?
I new in Xcode, I'm still learning it, but I could figure out how to pass data between ViewControllers.
Here is my working code:
FirstViewController.h:
#import <UIKit/UIKit.h>
#interface FirstViewController : UIViewController
- (IBAction)displayView:(id)sender;
#property (weak, nonatomic) IBOutlet UILabel *lblFirst;
#end
FirstViewController.m:
#import "FirstViewController.h"
#import "SecondViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize lblFirst;
SecondViewController *secondViewController;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
secondViewController = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
secondViewController.forwarded_lblFirst = lblFirst;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)displayView:(id)sender {
[self.view addSubview:secondViewController.view];
}
#end
SecondViewController.h:
#import <UIKit/UIKit.h>
#interface SecondViewController : UIViewController
#property (nonatomic, retain) UILabel *forwarded_lblFirst;
#property (weak, nonatomic) IBOutlet UITextField *txtSecond;
- (IBAction)btnReturn:(id)sender;
- (IBAction)txtSecond_DidEndOnExit:(id)sender;
- (IBAction)btnSecond:(id)sender;
#end
SecondViewController.m:
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
#synthesize forwarded_lblFirst;
#synthesize txtSecond;
- (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.
}
- (IBAction)btnReturn:(id)sender {
[self.view removeFromSuperview];
}
- (IBAction)txtSecond_DidEndOnExit:(id)sender {
forwarded_lblFirst.text = txtSecond.text;
[txtSecond resignFirstResponder];
[self.view removeFromSuperview];
}
- (IBAction)btnSecond:(id)sender {
forwarded_lblFirst.text = txtSecond.text;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[txtSecond resignFirstResponder];
}
#end
This code is working perfectly, the text what I enter on the SecondViewController's textbox (after pressing the btnSecond or simply the Return key on the keyboard) appears as the text of the Label on the FirstViewController.
My problem is, that when I do the exact same thing, but with a Tab Bar Application, the Label on the First tab won't change.
I can use the exact same code (except the changing-views part, because I handle on the first app with programmed buttons, but for the Tab-Bar-App there are already the buttons), there are also two ViewControllers for the Tab Bar App, too (one for each tabs).
So the code is the same, line by line, character by character, and the files are the same, too, for both apps (View-Based, Tab-Bar).
Why isn't my code working? How can I solve this problem?
Thank you!
You need to read some articles about transferring data between views:
Passing Data between View Controllers
Storyboard
passing data between views
iPhoneDevSDK
Talking about your problem, try this approach:
Add the property to your Application Delegate.
When assigning the property do something like:
MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
delegate.myProperty = #"My Value";
then, in your different tabs, you can retrieve this property in the same manner:
MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *valueInTab = delegate.myProperty;
A different approach to this problem is to use an independent data model.
Create an object that provides access and manipulation methods for all the data that your application needs to save, load, share, or use in any non-trivial way. Make the object available either as a Singleton or as a property of the application delegate. When changes happen, have the data model update application state. When something needs to be displayed, have the controller fetch it from the data model and send it to the view (MVC!).
If you don't store things in controllers that actually belong in the model, you never need to worry about passing information from controller to controller.
You need to use tabbardelegate in your secondview controller, assuming that you use this schema
FirstViewController.h
#import <UIKit/UIKit.h>
#interface FirstViewController : UIViewController
#property (strong, nonatomic) NSString *content;
#end
SecondViewController.m
#import "SecondViewController.h"
#import "FirstViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.tabBarController.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
if ([viewController isKindOfClass:[FirstViewController class]]){
FirstViewController *vc =( FirstViewController *) viewController;
vc.content = #"your content";
}
return TRUE;
}