I have two view controllers: view controller and viewcontroller2nd. I have UILabel in one of them and would like to change it when the button( named Go) in the viewcontroller2nd is clicked. I am using delegates and protocols to do it.
The code looks like this:
ViewController.h
#import <UIKit/UIKit.h>
#import "ViewController2nd.h"
#interface ViewController : UIViewController <SecondViewControllerDelegate>
{
IBOutlet UILabel *lbl;
ViewController2nd *secondview;
}
-(IBAction)passdata:(id)sender;
#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.
}
-(void) changeLabel:(NSString*)str{
lbl.text = str;
}
-(IBAction)passdata:(id)sender{
ViewController2nd *second = [[ViewController2nd alloc] initWithNibName:nil bundle:nil];
[self presentViewController:second animated:YES completion:NULL];
}
#end
Viewcontroller2nd.h
#import <UIKit/UIKit.h>
#protocol SecondViewControllerDelegate <NSObject>
#optional
-(void) changeLabel:(NSString*)str;
#end
#interface ViewController2nd : UIViewController{
IBOutlet UIButton *bttn;
id <SecondViewControllerDelegate> delegate;
}
#property (retain) id delegate;
-(IBAction)bttnclicked;
-(IBAction)back:(id)sender;
#end
ViewController2nd.m
#import "ViewController2nd.h"
#import "ViewController.h"
#interface ViewController2nd ()
#end
#implementation ViewController2nd
#synthesize delegate;
- (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.
}
-(IBAction)bttnclicked{
[[self delegate] changeLabel:#"Hello"];
}
-(IBAction)back:(id)sender{
[self dismissViewControllerAnimated:YES completion:NULL];
}
#end
The passing of the control between the two views is working correctly. However, when i click the go button in the viewcontroller2nd, it doesn't change the value of the label to Hello. What is wrong with the code? Need some guidance.
It seems you never set the delegate.
You can do it in your passData method :
-(IBAction)passdata:(id)sender{
ViewController2nd *second = [[ViewController2nd alloc] initWithNibName:nil bundle:nil];
second.delegate = self;
[self presentViewController:second animated:YES completion:NULL];
}
Hm, try the following in your changeLabel delegate method:
-(void) changeLabel:(NSString*)str{
lbl.text = str;
[lbl setNeedsDisplay];
}
EDIT:
Other than that:
Your label is a IBOutlet, right? Did you connect the label in your xib with the IBOutlet property (i.e. lbl) correctly in interface builder with the files owner
If you want to do this by using delegates then change passdata like:
-(IBAction)passdata:(id)sender
{
ViewController2nd *second = [[ViewController2nd alloc] initWithNibName:nil bundle:nil];
[second setDelegate:self];
[self presentViewController:second animated:YES completion:NULL];
}
You can do this without delegates.
Just create a object of ViewController in secondView and synthesize it like:
#import "ViewController.h"
#interface ViewController2nd : UIViewController
{
IBOutlet UIButton *bttn;
ViewController *parent;
}
#property (nonatomic, assign) ViewController *parent;
-(IBAction)bttnclicked;
-(IBAction)back:(id)sender;
#end
and in the passdata change it like
-(IBAction)passdata:(id)sender
{
ViewController2nd *second = [[ViewController2nd alloc] initWithNibName:nil bundle:nil];
[second setParent:self];
[self presentViewController:second animated:YES completion:NULL];
}
and change the bttnclicked like:
-(IBAction)bttnclicked
{
[parent changeLabel:#"Hello"];
}
I wrote following for you!
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *label;
#end
#import "ViewController.h"
#import "ViewController2.h"
#interface ViewController () <ViewController2Delegate>
#end
#implementation ViewController
-(void)passdata:(NSString *)data
{
self.label.text = data;
}
- (IBAction)buttonClicked:(id)sender {
ViewController2 *v = [[ViewController2 alloc] initWithNibName:#"ViewController2" bundle:nil];
v.delegate = self;
[self presentViewController:v animated:YES completion:nil];
}
#end
#import <UIKit/UIKit.h>
#protocol ViewController2Delegate <NSObject>
- (void)passdata:(NSString*)data;
#end
#interface ViewController2 : UIViewController
#property(assign, nonatomic) id<ViewController2Delegate> delegate;
#end
#import "ViewController2.h"
#interface ViewController2 ()
#end
#implementation ViewController2
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (IBAction)buttonClicked:(id)sender {
[self.delegate passdata:#"hello"];
}
- (IBAction)backButtonClicked:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
You don't need to import the header "ViewController2nd.h" in the both ViewController.h and ViewController.m
You declare the UILabel without property like, #property (strong, nonatomic).
May be, You didn't properly map the UILabel to your .storyboard or .xib file.
You forget to assign the second view controller delegate while calling the controller
ViewController2nd *second = [[ViewController2nd alloc] initWithNibName:nil bundle:nil];
second.delegate = self;
[self presentViewController:second animated:YES completion:NULL];
If anyone is using storyboard for viewcontrollers navigation.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier hasPrefix:#"view_to_capture"]) {
ViewController2nd *destination = segue.destinationViewController;
destination.delegate = self;
}
}
Related
Could anyone please explain to me why this isn't working? I think it is a real simple problem, but for some reason I am not getting it.
My problem: I have a NSString in my firstViewController with value "Hello!". Now I want to display this value in my secondViewController but the output is null.
This is my NSLog
2013-03-09 foo[95381:c07] value of foo in BITfirstViewcontroller: Hello!
2013-03-09 foo[95381:c07] value of foo in BITsecondViewcontroller: (null)
BITAppDelegate.m
#import "BITAppDelegate.h"
#import "BITfirstViewController.h"
#implementation BITAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
BITfirstViewController *fvc = [[BITfirstViewController alloc]init];
// Create navigationController and set InputViewController as root for navController
UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:fvc];
[self.window setRootViewController:navController];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
BITfirstViewController.h
#import <UIKit/UIKit.h>
#interface BITfirstViewController : UIViewController
#property (strong, nonatomic) NSString *foo;
-(IBAction)showSecondView:(id)sender;
#end
BITfirstViewController.m
#import "BITfirstViewController.h"
#import "BITsecondViewController.h"
#interface BITfirstViewController ()
#end
#implementation BITfirstViewController
#synthesize foo;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
foo = [NSString stringWithFormat:#"Hello!"];
NSLog(#"value of foo in BITfirstViewcontroller: %#",foo);
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(showSecondView:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)showSecondView:(id)sender;
{
BITsecondViewController *svc = [[BITsecondViewController alloc]init];
[self.navigationController pushViewController:svc animated:YES];
}
#end
BITsecondViewController.h
#import <UIKit/UIKit.h>
#class BITfirstViewController;
#interface BITsecondViewController : UIViewController
#property (nonatomic, retain) BITfirstViewController *fvc;
#end
BITsecondViewController.m
#import "BITsecondViewController.h"
#import "BITfirstViewController.h"
#interface BITsecondViewController ()
#end
#implementation BITsecondViewController
#synthesize fvc;
- (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.
NSLog(#"value of foo in BITsecondViewcontroller: %#", fvc.foo);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Try this in BITfirstViewController.m
-(IBAction)showSecondView:(id)sender;
{
BITsecondViewController *svc = [[BITsecondViewController alloc]init];
svc.fvc = self; // you need to set this property as you prepare the svc
[self.navigationController pushViewController:svc animated:YES];
}
EDIT:
Your fvc and svc are encapsulated, and don't have direct knowledge about each-other except though the use of properties (at least that's the way we try to do things in OOP). So, you were correct in creating a #property in your svc that allowed you to have a handle to your fvc, but [[BITsecondViewController alloc]init] will simply initialize that pointer to nil. Then you need to set that property to point to the intended object, which in this case is the fvc. Since the svc is being build from inside an instance of BITFirstViewController, the correct handle to pass in is self.
I'm trying to change UITextView.text from SecondViewController in ViewController. I can do it if it was NSString type in SecondViewController by doing:
SVC.string = #"test";
The problem is that:
messageBox.text doesn't change
SVC.messageBox.text returns (null)
One of the methods in ViewController.m:
SecondViewController *SVC = [[SecondViewController alloc]initWithNibName:#"SecondViewController" bundle:nil];
SVC.messageBox.text = #"changed";
NSLog(#"SVC: %#", SVC.messageBox.text); // result = (null)
[self presentViewController:SVC animated:YES completion:NULL];
SecondViewController.h:
#import <UIKit/UIKit.h>
#interface SecondViewController : UIViewController
#property (nonatomic) IBOutlet UITextView *messageBox;
#end
SecondViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.messageBox.text = #"first";
}
How to get over with this?
Try this,
One of the methods in ViewController.m:
SecondViewController *SVC = [[SecondViewController alloc]initWithNibName:#"SecondViewController" bundle:nil];
SVC.strMessage= #"changed";
[self presentViewController:SVC animated:YES completion:NULL];
SecondViewController.h:
#import <UIKit/UIKit.h>
#interface SecondViewController : UIViewController
{
IBOutlet UITextView *messageBox;
}
#property (nonatomic) NSString *strMessage;
#end
SecondViewController.m:
#synthesize strMessage;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.messageBox.text = strMessage;
}
You can use delegates to do it as well.
Example:
Viewcontroller2nd.h
#protocol SecondViewControllerDelegate <NSObject>
#optional
-(void) changeLabel:(NSString*)str;
#end
#interface ViewController2nd : UIViewController{
IBOutlet UIButton *bttn;
id <SecondViewControllerDelegate> delegate;
}
#property (retain) id delegate;
#end
Viewcontrollerone.h
#interface ViewController : UIViewController <SecondViewControllerDelegate>
{
IBOutlet UILabel *lbl;
}
-(IBAction)passdata:(id)sender;
#end
Viewcontrollerone.m
-(void) changeLabel:(NSString*)str{
lbl.text = str;
}
More about delegates:http://developer.apple.com/library/ios/#documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html
Hope this helps...
The problem with your code is your accessing the uicontrols which are not yet created in the memory.
You have to change the order of the execution of your statements like this...
SecondViewController *SVC = [[SecondViewController alloc]initWithNibName:#"SecondViewController" bundle:nil];
[self presentViewController:SVC animated:YES completion:NULL];
SVC.messageBox.text = #"changed";
NSLog(#"SVC: %#", SVC.messageBox.text);
Set #property (nonatomic) IBOutlet UITextView *messageBox; to #property (nonatomic, strong) IBOutlet UITextView *messageBox; and check if you have connected it with UItextView. And don't reset it in viewDidLoad. Another thing you can try is:
SecondViewController *SVC = [[SecondViewController alloc]initWithNibName:#"SecondViewController" bundle:nil];
[self presentViewController:SVC animated:YES completion:NULL];
SVC.messageBox.text = #"changed";
NSLog(#"SVC: %#", SVC.messageBox.text); // result = (null)
Along with what mentioned above.
just property-synthesize string andf just assign this string to yourTextView.text. For example see bellow..
#interface SecondViewController : UIViewController{
NSString *strMsgText;
}
#property(nonatomic, retain) NSString *strMsgText;
#end
#implementation SecondViewController
#synthesize strMsgText;
after that when you present SecondViewController at that time assign your value like bellow..
SecondViewController *SVC = [[SecondViewController alloc]initWithNibName:#"SecondViewController" bundle:nil];
SVC.strMsgText = #"changed";
[SVC.strMsgText retain];
[self presentViewController:SVC animated:YES completion:NULL];
and in viewDidLoad: method of SecondViewController just assign that string to messageBox(TextView), like bellow...
- (void)viewDidLoad
{
messageBox.text = strMsgText;
}
I have been stuck here.
I have a NSString in Appdelegate. And I have two views called firstview,second view.In first view I have a label and set text from stringvariable which is in Appdelegate .When I click on the button in first view,It goes to the secondview(added the second view to first view as a subview).In second view I have a back button.when I click the back button it is displaying the first view ( Here I am setting the value which is in the appdelegate.And then used this [self.view removeFromSuperview]).The Problem is first view is appearing but label value is not updating.Can any body tell me how to update the Labeltext.Kindly tell me.
Appdelegate.h
#import <UIKit/UIKit.h>
#class FirstView;
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSString *str1;
}
#property (nonatomic,retain) NSString *str1;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
#end
Appdelegate.m
#import "AppDelegate.h"
#import "FirstView.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
#synthesize str1;
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[FirsView alloc] initWithNibName:#"FirstView" bundle:nil] autorelease];
self.str1 = #"view1";
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
FirstView.h
#import <UIKit/UIKit.h>
#import "secondView.h"
#interface FirstView : UIViewController
{
IBOutlet UILabel *btn;
secondView *cont;
}
-(IBAction)gotoView2:(id)sender;
#end
FirstView.m
#import "FirstView.h"
-(IBAction)gotoView2:(id)sender
{
cont = [[secondView alloc] initWithNibName:#"secondView" bundle:nil];
[self.view addSubview:cont.view];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *del = [[UIApplication sharedApplication] delegate];
[btn setTitle:del.str1];
}
**SecondView.h**
#import <UIKit/UIKit.h>
#interface SecondView : UIViewController
{
}
-(IBAction)goBack:(id)sender;
#end
SecondView
#import "SecondView.h"
#import "AppDelegate.h"
#implementation SecondView
-(IBAction)gotoView1:(id)sender
{
AppDelegate *del = [[UIApplication sharedApplication] delegate];
[del setStr1:#"Home"];
[self.view removeFromSuperView];
}
There is a pattern how to do such things. You should define a protocol like this:
#protocol FirstViewDelegate <NSObject>
- (void)didDismissSecondView;
#end
Your first view should conform to this protocol:
#interface FirstView: UIViewController <FirstViewDelegate> {
...
in its implementation add function didDismissSecondView:
- (void) didDismissSecondView
{
AppDelegate *del = [[UIApplication sharedApplication] delegate];
[btn setTitle:del.str1];
}
Your second view has to have a property
#interface SecondView : UIViewController
{
id<FirstViewDeledate> delegate;
}
#property (nonatomic, retain) id<FirstViewDeledate> delegate;
When you show your second view from the first view set its delegate to self of first view
in your function:
-(IBAction)gotoView2:(id)sender
{
SecondView *aView = [[SecondView alloc] init] // or whatever
...//other initialization code
aView.delegate = self;
... // show it
}
and before you dismiss the second view:
-(IBAction)gotoView1:(id)sender
{
AppDelegate *del = [[UIApplication sharedApplication] delegate];
[del setStr1:#"Home"];
[self.delegate didDismissSecondView];
[self.view removeFromSuperView];
}
And you done.
A bit long, but works.
NEW CODE
DatePickerViewController.h
#import <UIKit/UIKit.h>
#protocol DatePickerViewControllerDelegate;
#interface DatePickerViewController : UIViewController {
IBOutlet UIDatePicker *datePicker;
id<DatePickerViewControllerDelegate> delegate;
}
#property (retain) IBOutlet UIDatePicker *datePicker;
#property (assign) id<DatePickerViewControllerDelegate> delegate;
NSInteger buttonPressed;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
- (IBAction)doneButtonPressed:(id)sender;
#end
#protocol DatePickerViewControllerDelegate <NSObject>
#optional
-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;
#end
DatePickerViewController.m
#import "DatePickerViewController.h"
#implementation DatePickerViewController
#synthesize datePicker, delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
self.title = #"Date Picker";
}
return self;
}
- (void)viewDidLoad {
NSLog(#"Date Picker. viewDidLoad");
[super viewDidLoad];
double days = 2.0f;
datePicker.date = [NSDate dateWithTimeIntervalSinceNow:60.0f * 60.0f * 24.0f * days];
}
//-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;
- (IBAction)doneButtonPressed:(id)sender
{
if ([self.delegate respondsToSelector:#selector(datePickerViewController:didChooseDate:)]) {
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateString = [dateFormatter stringFromDate:[datePicker date]];
[self.delegate datePickerViewController:self didChooseDate:dateString];
[self dismissModalViewControllerAnimated:YES];
}
}
- (void)dealloc {
[datePicker release];
[super dealloc];
}
#end
DatePickerViewController2.h
#import <UIKit/UIKit.h>
#protocol DatePickerViewController2Delegate;
#interface DatePickerViewController2 : UIViewController {
IBOutlet UIDatePicker *datePicker2;
id<DatePickerViewController2Delegate> delegate;
}
#property (retain) IBOutlet UIDatePicker *datePicker2;
#property (assign) id<DatePickerViewController2Delegate> delegate;
NSInteger buttonPressed2;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
- (IBAction)doneButtonPressed2:(id)sender;
#end
#protocol DatePickerViewController2Delegate <NSObject>
#optional
-(void)datePickerViewController2:(DatePickerViewController2 *)controller didChooseDate:(NSString *)chosenDate;
#end
DatePickerViewController2.m
#import "DatePickerViewController2.h"
#implementation DatePickerViewController2
#synthesize datePicker2, delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
self.title = #"Date Picker2";
}
return self;
}
- (void)viewDidLoad {
NSLog(#"Date Picker2. viewDidLoad");
[super viewDidLoad];
double days = 2.0f;
datePicker2.date = [NSDate dateWithTimeIntervalSinceNow:60.0f * 60.0f * 24.0f * days];
}
//-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;
- (IBAction)doneButtonPressed2:(id)sender
{
if ([self.delegate respondsToSelector:#selector(datePickerViewController2:didChooseDate:)]) {
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateString = [dateFormatter stringFromDate:[datePicker2 date]];
[self.delegate datePickerViewController2:self didChooseDate:dateString];
[self dismissModalViewControllerAnimated:YES];
}
}
- (void)dealloc {
[datePicker2 release];
[super dealloc];
}
#end
DatePickerModalExampleAppDelegate.h
#import <UIKit/UIKit.h>
#class DatePickerModalExampleViewController;
#interface DatePickerModalExampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
DatePickerModalExampleViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet DatePickerModalExampleViewController *viewController;
#end
DatePickerModalExampleAppDelegate.m
#import "DatePickerModalExampleAppDelegate.h"
#import "DatePickerModalExampleViewController.h"
#implementation DatePickerModalExampleAppDelegate
#synthesize window;
#synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
DatePickerModalExampleViewController.h
#import <UIKit/UIKit.h>
#import "DatePickerViewController.h"
#import "DatePickerViewController2.h"
#interface DatePickerModalExampleViewController : UIViewController <DatePickerViewControllerDelegate> {
IBOutlet UIButton *button;
IBOutlet UIButton *button2;
IBOutlet UIButton *button3;
}
#property(nonatomic, retain) IBOutlet UIButton *button;
#property(nonatomic, retain) IBOutlet UIButton *button2;
#property(nonatomic, retain) IBOutlet UIButton *button3;
-(IBAction)buttonPressed:(id)sender;
-(IBAction)buttonPressed2:(id)sender;
#end
DatePickerModalExampleViewController.m
#import "DatePickerModalExampleViewController.h"
#implementation DatePickerModalExampleViewController
#synthesize button;
#synthesize button2;
#synthesize button3;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
-(IBAction)buttonPressed:(id)sender{
NSLog(#"I was pressed");
buttonPressed = ((UIButton *)sender).tag;
DatePickerViewController *datePickerViewController = [[DatePickerViewController alloc] initWithNibName:#"DatePickerViewController" bundle:nil];
datePickerViewController.delegate = self;
[self presentModalViewController:datePickerViewController animated:YES];
[datePickerViewController release];
switch (((UIButton*)sender).tag)
{
case 100001:
NSLog(#"Button 1 was pressed");
//some code
break;
case 100002:
NSLog(#"Button 2 was pressed");
//some code
break;
}
}
-(IBAction)buttonPressed2:(id)sender{
NSLog(#"I was pressed2");
buttonPressed2 = ((UIButton *)sender).tag;
DatePickerViewController2 *datePickerViewController2 = [[DatePickerViewController2 alloc] initWithNibName:#"DatePickerViewController2" bundle:nil];
datePickerViewController2.delegate = self;
[self presentModalViewController:datePickerViewController2 animated:YES];
[datePickerViewController2 release];
switch (((UIButton*)sender).tag)
{
case 100003:
NSLog(#"Button 3 was pressed");
//some code
break;
}
}
-(void)viewDidLoad{
[super viewDidLoad];
self.button.tag = 100001;
self.button2.tag = 100002;
self.button3.tag = 100003;
buttonPressed = -1;
buttonPressed2 = -1;
}
-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate{
NSLog(#"Chosen Date as String: %#", chosenDate );
if (buttonPressed == -1)
return;
UIButton *buttonToSet = (UIButton*)[self.view viewWithTag:buttonPressed];
buttonPressed = -1;
[buttonToSet setTitle: chosenDate forState: UIControlStateNormal];
[self dismissModalViewControllerAnimated:YES];
}
-(void)datePickerViewController2:(DatePickerViewController2 *)controller didChooseDate:(NSString *)chosenDate{
NSLog(#"Chosen Date as String: %#", chosenDate );
if (buttonPressed2 == -1)
return;
UIButton *buttonToSet = (UIButton*)[self.view viewWithTag:buttonPressed2];
buttonPressed2 = -1;
[buttonToSet setTitle: chosenDate forState: UIControlStateNormal];
[self dismissModalViewControllerAnimated:YES];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[button3 release];
[button2 release];
[button release];
[super dealloc];
}
#end
Hello you can set the property "tag" on button to identify it
Uncomment
- (void)viewDidLoad {
[super viewDidLoad];
}
And type :
- (void)viewDidLoad {
[super viewDidLoad];
self.button.tag = 100001;
self.button2.tag = 100002;
}
then
turn in DatePickerModalExampleViewController.h
(IBAction)buttonPressed to (IBAction)buttonPressed:(id)sender;
Then turn in DatePickerModalExampleViewController.m
-(IBAction)buttonPressed to -(IBAction)buttonPressed:(id)sender
and in DatePickerModalExampleViewController.m this method could be like that :
-(IBAction)buttonPressed:(id)sender
{
switch(((UIButton*)sender).tag)
{
case 100001
NSLog(#"Button 1 was pressed");
DatePickerViewController *datePickerViewController =[DatePickerViewController alloc] initWithNibName:#"DatePickerViewController" bundle:nil];
datePickerViewController.delegate = self;
[self presentModalViewController:datePickerViewController animated:YES];
[datePickerViewController release];
break;
case 100002 :
NSLog(#"Button 2 was pressed");
// some code
break;
}
}
As you use the interfacebuilder I'm not friend with it but you must relink your actions
I'm writting from my PC so without xcode some code can contains syntax error be carreful. but it's the main idea.
Use tag for both buttons and check the condition accordingly...
I am using code from Ed Marty's answer for the question here but am having real trouble with a few bits.
On the click of a button I have got the datepicker appearing, but the 'done' button however isn't. I am also getting an error from the line:
[delegate datePickerController:controller didPickDate:datePicker.date];
Error message:
'controller' undeclared (first use in this function)
All in all I have 6 files:
ModalDatePickerViewController.m
ModalDatePickerViewController.h
ModalDatePickerAppDelegate.m
ModalDatePickerAppDelegate.h
DatePickerController.m
DatePickerController.h
My DatePickerController.h is looking like:
#import <UIKit/UIKit.h>
#class DatePickerController;
#protocol DatePickerControllerDelegate
- (void) datePickerController:(DatePickerController *)controller didPickDate:(NSDate *)date;
#end
#interface DatePickerController : UIViewController {
UIDatePicker *datePicker;
NSObject <DatePickerControllerDelegate> *delegate;
}
#property (nonatomic, retain) UIDatePicker *datePicker;
#property (nonatomic, assign) NSObject <DatePickerControllerDelegate> *delegate;
#end
and the DatePickerController.m:
#import "DatePickerController.h"
#implementation DatePickerController
#synthesize datePicker;
#synthesize delegate;
- (void) loadView {
self.view = [[[UIView alloc] init] autorelease];
self.datePicker = [[[UIDatePicker alloc] init] autorelease];
[self.view addSubview:self.datePicker];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Done" forState:UIControlStateNormal];
button.center = CGPointMake(160,230);
[button addTarget:self action:#selector(done) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:button];
}
- (void) done {
[delegate datePickerController:controller didPickDate:datePicker.date];
}
- (void) dealloc {
[datePicker release];
[super dealloc];
}
#end
On the main view I have a button that call this class as below:
#import "ModalDatePickerViewController.h"
#implementation ModalDatePickerViewController
- (void) pickDate {
DatePickerController *screen = [[[DatePickerController alloc] init] autorelease];
screen.delegate = self;
[self presentModalViewController:screen animated:YES];
}
- (void) datePickerController:(DatePickerController *)controller didPickDate:(NSDate *)date {
//[self doSomethingWithDate:date];
[controller dismissModalViewControllerAnimated:YES];
}
- (IBAction)HitMe:(id)sender {
[self pickDate];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
[super dealloc];
}
#end
and:
#import <UIKit/UIKit.h>
#import "DatePickerController.h"
#interface ModalDatePickerViewController : UIViewController <DatePickerControllerDelegate> {
}
- (IBAction)HitMe:(id)sender;
#end
On this line:
[delegate datePickerController:controller didPickDate:datePicker.date];
try replacing controller with self.