How to get UIDatePicker value in the UILabel on button click? - iphone

Please help me to get the value of UIDatePicker to UILabel on button click for an iPhone application.

Create an outlet and then just ask its value
-(IBAction)OnButtonClick:(id)sender
{
NSDate *date = datePicker.date;
label.text = [date description];
}

DatePicker=[[UIDatePicker alloc]init];
[DatePicker setDatePickerMode:UIDatePickerModeDate];
//[DatePicker setMaximumDate:[NSDate date]];
[DatePicker setMinimumDate:[NSDate date]];
[DatePicker addTarget:self action:#selector(updateDate:)
forControlEvents:UIControlEventValueChanged];
-(void) doneButton
{
[self updateDate:DatePicker]; //calling this fuction on inside the button
}
-(void)updateDate:(UIDatePicker *)sender
{
NSDate *date = self.DatePicker.date;
_dateFormat = [[NSDateFormatter alloc]init];
[_dateFormat setDateFormat:#"MM/dd/yyyy"];
DateTextField.text = [_dateFormat stringFromDate:date];
}

Swift 2.0
#IBAction func buttonPressed(sender: AnyObject) {
let date: NSDate = timePicker.date
label.text = date.description
}

Related

DatePicker for UITextfield,should I use NSDatePicker?

I have a UITextfield "Birthday" and right now after clicking on the text field I have a keyboard and I would like to change it to a datepicker.
Is there anyone who can help step by step with this?what should I add to my code and what changes do I need to make.
Here is what I have for my UITextField "Birthady":
field = [[UITextField alloc] initWithFrame:frame];
[self.appDel.styleManager decorateTextField:field];
field.placeholder = #"Birthday";
[container addSubview:field];
self.registrationFormBirthday = field;
self.registrationFormBirthday.delegate = self;
Based on Jonathan answer this is what I have right now:
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
if textField == XtextLabel
{
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] ;
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init] ;
[comps setYear:-0];
NSDate *maximumDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps setYear:-90];
NSDate *minimumDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[datePicker setMaximumDate:maximumDate];
[datePicker setMinimumDate:minimumDate];
datePicker.datePickerMode = UIDatePickerModeDate;
textField.inputView = datePicker;
}
}
How Can I show the selected date on in the XtextLabel and exit datePicker?
Something like...
UIDatePicker *datePicker = [[[UIDatePicker alloc] init]];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:#selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
textField.inputView = datePicker;
- (IBAction)datePickerValueChanged:(id)sender {
NSDate *pickerDate = [sender date]; //Do something with the date
}

iOS - removing subview that added programmatically and printing date in label

I need some help related to iOS application
On clicking the button I added a DatePicker programmatically and now I am not able to remove the view this is my code
I also tried to put the date in label dateLabel but it shows some run time error because it is not a string format I tried some other method also like NSDateFormatter but I am not getting the proper result
-(IBAction)date:(id)sender{
UIDatePicker *datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(420, 320, 300, 500)];
[datePicker addTarget:self action:#selector(Pick:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
NSData *date=[datePicker date];
NSLog(#"%#",date);
dateLabel.text=date;
}
-(void)Pick:(id)sender{
[datePicker removeFromSuperview];
}
Do like this
-(IBAction)date:(id)sender
{
datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(420, 320, 300, 500)];
[datePicker addTarget:self action:#selector(Pick:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
}
-(void)Pick:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = kCFDateFormatterShortStyle;
label.text=[NSString stringWithFormat:#"%#",
[df stringFromDate:datePicker.date]];
[df release];
[datePicker removeFromSuperview];
datePicker=nil;
}
You are declaring the UIDatePicker *datePicker as a local variable.
It can be only accessible in the declared function (-(IBAction)date:(id)sender).
You need to declare it globally for using it in other functions.
Declare that variable in your .m file under
#interface className()
#property(nonatomic, strong) UIDatePicker *datePicker;
#end
Try this
Declare your datepicker in .h
UIDatePicker *datePicker;
and then
-(IBAction)date:(id)sender
{
datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(420, 320, 300, 500)];
[datePicker addTarget:self action:#selector(Pick:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
}
-(void)Pick:(id)sender
{
NSDate *date=[datePicker date];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateFormat:#"YYYY-MM-DD"];
NSString *dateSTr = [dateformatter stringFromDate:date];
NSLog(#"%#",dateSTr);
dateLabel.text=date;
[datePicker removeFromSuperview];
}

how to call date on cell selected from datepickerview in iphone

hi friend i have to make date application
i have groped tableview.i have one section and two row
when my application start i am showing default date on both cell on first cell i was showing today day+1 and on nextcell i am showing today day+6 they i can see but
- (id)init
{
[super initWithStyle:UITableViewStyleGrouped];
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:1];
app.selectionData.fromDateSelected = [gregorian dateByAddingComponents:dateComponents toDate:todaysDate options:0];
[dateComponents release];
[gregorian release];
//this is for 6day
NSDate *todaysDate1 = [NSDate date];
NSCalendar *gregorian1 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents1 = [[NSDateComponents alloc] init];
[dateComponents1 setDay:6];
app.selectionData.toDateSelected = [gregorian1 dateByAddingComponents:dateComponents1 toDate:todaysDate1 options:0];
[dateComponents1 release];
[gregorian1 release];
return self;
}
but know i want if
the first cell selected date is changed from date pickerview and second cell date is less than the first cell selected date then change the second cell date automatically to first cell selected date+5 please help me how to solve it what the change i have to do in my code wher i am show by default this for once time on this this is my code on run time
this code i writemin my firstview controller class where i am show this date when my application start
in tableviewcellrowAtindexpath
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
NSString*fromDate = [dateFormat stringFromDate:app.selectionData.fromDateSelected];
// NSString *toDate = [dateFormat stringFromDate:targetDate1];
NSString *toDate = [dateFormat stringFromDate:app.selectionData.toDateSelected];
if ([indexPath row] == 0 && [indexPath section] == 1)
{
cell.textLabel.text=#"From Date";
cell.detailTextLabel.text=fromDate;
NSLog(#"this is for fromDate:%#",fromDate);
}
if ([indexPath row] == 1 && [indexPath section] == 1)
{
cell.textLabel.text=#"To Date";
cell.detailTextLabel.text=toDate;
}
[dateFormat release];
dateFormat = nil;
this is code od dateview where i put my datepicker from here i selected date
- (void)viewDidLoad
{
// if(datePicker != nil && [datePicker retainCount] > 0)
// {
// [datePicker release];
//
// datePicker = nil;
//}
datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 0, 0)];
[datePicker addTarget:self action:#selector(DateChangeForFinalPayMent) forControlEvents:UIControlEventValueChanged];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.date = [NSDate date];
datePicker.minimumDate = [NSDate date];
[self.view addSubview:datePicker];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)DateChangeForFinalPayMent{
if ([selectionData type] == 0)
[selectionData setFromDateSelected:[datePicker date]];
else
[selectionData setToDateSelected:[datePicker date]];
// [super viewWillDisappear:animated];
}
I wrote an example project for you that does this
Basically - look at the delegate method of the picker view controller.
It sends back a new date - and from that date you can calculate the second date and reload your table view.
This is the code to get date from datepicker. 1st select the date & then select the cell you need to update.
NSString *dateString = nil;
-(void)DateChangeForFinalPayMent:(id)sender {
NSLocale *usLocale = [[[NSLocale alloc]initWithLocaleIdentifier:#"en_US"] autorelease];
NSDate *pickerDate = [self.datePicker date];
NSString *selectionString = [[NSString alloc] initWithFormat:#"%#", [pickerDate descriptionWithLocale:usLocale]];
NSLog(#"string =%#",selectionString);
dateString = selectionString;
[selectionString release];
}
On selecting the cell Perform this operation
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
selectedIndex = indexPath.row;
NSArray *array = [NSArray arrayWithObject:indexPath];
[tablview reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//some condition over here
if(selectedIndex == indexPath.row)
cell.textLabel = dateString;
//some condition over her
}
You use this code according to your implementation..

Xcode Saving UIDatepicker to be displayed in a label

The following code is to show my UIDatepicker:
- (IBAction)showActionSheet:(id)sender {
NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? #"\n\n\n\n\n\n\n\n\n" : #"\n\n\n\n\n\n\n\n\n\n\n\n" ;
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:[NSString stringWithFormat:#"%#%#", title, NSLocalizedString(#"Please Select A Date", #"")]
delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:#"I've Made My Choice", nil];
[actionSheet showInView:self.view];
UIDatePicker *datePicker = [[[UIDatePicker alloc] init] autorelease];
datePicker.datePickerMode = UIDatePickerModeDate;
[actionSheet addSubview:datePicker];
}
It all works properly, but what I'd like to do is to display the users choice into a label which I have named " label1 ". Can anyone help? Thanks!
UPDATE:
Here is the updated code:
- (IBAction)showActionSheet:(id)sender {
NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? #"\n\n\n\n\n\n\n\n\n" : #"\n\n\n\n\n\n\n\n\n\n\n\n" ;
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:[NSString stringWithFormat:#"%#%#", title, NSLocalizedString(#"Please Select A Date", #"")]
delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:#"I've Made My Choice", nil];
[actionSheet showInView:self.view];
UIDatePicker *datePicker = [[[UIDatePicker alloc] init] autorelease];
datePicker.datePickerMode = UIDatePickerModeDate;
[actionSheet addSubview:datePicker];
[datePicker addTarget:self
action:#selector(updateLabel:)
forControlEvents:UIControlEventValueChanged];
}
- (void)updateLabel:(id)sender {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
label1.text = [NSString stringWithFormat:#"%#",[df stringFromDate:datePicker.date]];
[df release];
/* the following allows you to choose the date components
NSCalendar *calendar = [NSCalendar currentCalendar];
int hour = [[calendar components:NSHourCalendarUnit fromDate:[datePicker date]] hour];
int minute = [[calendar components:NSMinuteCalendarUnit fromDate:[datePicker date]] minute];
int year = [[calendar components:NSYearCalendarUnit fromDate:[datePicker date]] year];
int month = [[calendar components:NSMonthCalendarUnit fromDate:[datePicker date]] month];
int day = [[calendar components:NSDayCalendarUnit fromDate:[datePicker date]] day];
*/
}
That's for the .m , my .xib has the 'label' tied properly too :) just getting a (null) value whenever I choose my date :(
.h
#import <UIKit/UIKit.h>
#interface YourViewController : UIViewController {
IBOutlet UILabel *label1;
}
#property (nonatomic, retain) UILabel *label1;
#end
.m
#implementation YourViewController
#synthesize label1;
/*
All of your code goes here
*/
#end
Interface Builder
Also add the following to your showActionSheet:
[datePicker addTarget:self
action:#selector(updateLabel:)
forControlEvents:UIControlEventValueChanged];
This should update your label from datePicker:
-(void)updateLabel:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
label1.text = [NSString stringWithFormat:#"%#",[df stringFromDate:datePicker.date]];
[df release];
/* the following allows you to choose the date components
NSCalendar *calendar = [NSCalendar currentCalendar];
int hour = [[calendar components:NSHourCalendarUnit fromDate:[datePicker date]] hour];
int minute = [[calendar components:NSMinuteCalendarUnit fromDate:[datePicker date]] minute];
int year = [[calendar components:NSYearCalendarUnit fromDate:[datePicker date]] year];
int month = [[calendar components:NSMonthCalendarUnit fromDate:[datePicker date]] month];
int day = [[calendar components:NSDayCalendarUnit fromDate:[datePicker date]] day];
*/
}
Here I shows that UIDatePicker in UITableview cell.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
// Make a new view, or do what you want here
UIDatePicker *pv = [[UIDatePicker alloc] initWithFrame:CGRectMake(0,185,0,0)];
[self.view addSubview:pv];
return NO;
}
If you are using UITableView, then use following in order to show UIDatePicker instead of keyboard.
if (0 == indexPath.row) {
cell.rightTextField.placeholder = #”Date”;
cell.rightTextField.text = [coAccident strDateTime];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
UIDatePicker *datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, 185, 0)];
[datePicker addTarget:self action:#selector(changeDateInLabel :) forControlEvents:UIControlEventValueChanged];
cell.rightTextField.inputView = datePicker;
}
- (IBAction)changeDateInLabel:(id)sender {
UIDatePicker * datePicker = (UIDatePicker*)sender;
CAccidentVO* coAccident = [m_arrVehicles objectAtIndex:1];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
[coAccident setStrDateTime:[NSString stringWithFormat:#"%#",[df stringFromDate:datePicker.date]]];
[df release];
[m_tvVehicleDetails reloadData];
}

iPhone datepicker instead of keyboard?

How would you do that?
I have a form with a UITextField. When I click in it I would like to display a UIDatePicker instead of the default Keyboard that pops-up by default? Note that there are also other elements on my form.
I think this is a more official way to do this:
UIDatePicker *datePicker = [[[UIDatePicker alloc] init] autorelease];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:#selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
datePicker.tag = indexPath.row;
textField.inputView = datePicker;
in .h
UIDatePicker *datePicker;
NSDate *date;
UIToolbar *keyboardToolbar;
in ViewDidLoad:
if (keyboardToolbar == nil) {
keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
[keyboardToolbar setBarStyle:UIBarStyleBlackTranslucent];
UIBarButtonItem *extraSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *accept = [[UIBarButtonItem alloc] initWithTitle:#"Accept" style:UIBarButtonItemStyleDone target:self action:#selector(closeKeyboard:)];
[keyboardToolbar setItems:[[NSArray alloc] initWithObjects: extraSpace, accept, nil]];
}
self.txtDate.inputAccessoryView = keyboardToolbar;
datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:#selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
self.txtDate.inputView = datePicker;
- (void)datePickerValueChanged:(id)sender{
date = datePicker.date;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/YYYY"];
[self.txtDate setText:[df stringFromDate:date]];
}
in storyboard add to txtDate -> EditingDidEnd
- (IBAction)establishHour:(id)sender{
hour = hourPicker.date;
NSDateFormatter *hf = [[NSDateFormatter alloc] init];
[hf setDateFormat:#"HH:MM"];
[self.txtHour setText:[hf stringFromDate:hour]];
}
Sets the keyboard as DatePicker and created a toolbar with a button to accept the selection.
I've converted Johan Kool's answer into swift if anyone would like it. I placed the code in viewDidLoad.
let datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.addTarget(self, action: "datePickerValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
textField.inputView = datePicker
(IBAction)estableceHora:(id)sender{
Hora = horaPicker.date;
NSDateFormatter *hf = [[NSDateFormatter alloc] init];
[hf setDateFormat:#"HH:MM"];
[self.txtHora setText:[hf stringFromDate:Hora]];
}
Added in .h files :
UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
Added in .m files :
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
pTxtDate.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:[NSDate date]]];
NSLog(#"pTxtDate.text %#",pTxtDate.text);
[df release];
[self.view addSubview:pTxtDate];
[pTxtDate release];
DatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 325, 300)];
DatePicker.datePickerMode = UIDatePickerModeDate;
DatePicker.hidden = NO;
DatePicker.date = [NSDate date];
[DatePicker addTarget:self
action:#selector(LabelChange:)
forControlEvents:UIControlEventValueChanged];
[self.view addSubview:DatePicker];
[DatePicker release];
}
- (void)LabelChange:(id)sender {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
pTxtDate.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:DatePicker.date]];
}