DatePicker for UITextfield,should I use NSDatePicker? - iphone

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
}

Related

How to make a label show on a specific time in xcode

I'm making an iOS application for iPhone, and I want to have two labels that is hidden on a specific time and shown on a specific time. Like Label1 is shown between 6am and 6pm and Label2 is shown between 6pm and 6am
Any ideas?
[NSDate date]; gives you the current date .Use date fromatter to get the fromat you need and use setText: method to set the text.Fire it in a timer and set the text
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"EEEE MMMM d, YYYY"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
[yourLabel setText:[dateFormatter stringFromDate:[NSDate date]]];
EDIT
full code,Try this
-(void)showtext
{
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"hh:mm:ss"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
if( [self compareTimeIsbetween6])
{
[self.date1Label setHidden:NO];
[self.date2Label setHidden:YES];
[self.date1Label setText:[dateFormatter stringFromDate:[NSDate date]]];
}
else
{
[self.date1Label setHidden:YES];
[self.date2Label setHidden:NO];
[self.date2Label setText:[dateFormatter stringFromDate:[NSDate date]]];
}
}
-(BOOL)compareTimeIsbetween6
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinute = [components minute];
NSInteger currentSecond = [components second];
if (currentHour < 6 || (currentHour > 18 || (currentHour == 18 && (currentMinute > 0 || currentSecond > 0)))) {
return YES;
}
else
{
return NO;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(showtext) userInfo:nil repeats:YES]; // Do any additional setup after loading the view, typically from a nib.
}
.h
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *date1Label;
#property (weak, nonatomic) IBOutlet UILabel *date2Label;
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];
Now you have the hour, just add your normal logic.
if want to be change the formate do this...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm a"];
// another is [formatter setDateFormat:#"hh:mm:ss"];
NSLog(#"Current Date: %#", [formatter stringFromDate:today]);

iOS : Move forward dynamically NSDate with button

I have created a custom class for my dates and need move dates forward and backward via button . Here is my code which shows Today date :
- (NSString *) showToday {
NSCalendar *myCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setCalendar:myCal];
offsetComponents = [[NSDateComponents alloc] init];
//shows today
[offsetComponents setDay:0];
NSDate *nextDate = [myCal dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];
[dateFormatter setDateFormat:#"d"];
NSString *currDay = [dateFormatter stringFromDate:nextDate];
[NSString stringWithFormat:#"%#",currDay];
[myCal release];
[dateFormatter release];
return currDay;
}
on my viewController :
customClass = [[customClass alloc]init];
day.text = [cal showToday];
so if I need to move forward a date I just change this line code to :
//show tomorrow
[offsetComponents setDay:1];
so How can I dynamically change this line and change dates via button ?
You can declare an int for your offsetComponents variable. then :
- (IBAction)moveDatesForward:(id)sender {
NSCalendar *persCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSPersianCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *IRLocal = [[NSLocale alloc] initWithLocaleIdentifier:#"fa_IR"];
[dateFormatter setLocale:IRLocal];
[dateFormatter setCalendar:persCalendar];
offsetComponents = [[NSDateComponents alloc] init];
offsetComponents.day = _dayNumber;
NSDate *nextDate = [persCalendar dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];
[dateFormatter setDateFormat:#"d"];
dayLabel.text = [dateFormatter stringFromDate:nextDate];
[NSString stringWithFormat:#"%#",dayLabel];
[persCalendar release];
[dateFormatter release];
_dayNumber ++;
}
How about doing something like this:
(Uses ARC - Don't complain about memory leaks.)
- (void) refreshDateLabel
{
NSDateFormatter* dateFormatter = [NSDateFormatter new];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
self.dateLabel.text = [dateFormatter stringFromDate: self.date];
}
- (IBAction)forward:(id)sender
{
self.date = [self.date dateByAddingTimeInterval: 24 * 60 * 60];
[self refreshDateLabel];
}
- (IBAction)back:(id)sender
{
self.date = [self.date dateByAddingTimeInterval: -(24 * 60 * 60)];
[self refreshDateLabel];
}
Complete project at https://github.com/st3fan/StackOverflowAnswers/blob/master/DateSelection

UI Datepicker range. iPhone

I have a datePickerView which I want it to have a min date = current time, max date = 48hrs later. It's currently working fine, as I can't pick out of that range. But there's some aesthetic problems. Some of the period in that range is not in black. For example in the picture below, today's 7hour hand is suppose to be in black but its not.
- (void)viewDidLoad
{
[super viewDidLoad];
NSDate *now = [[NSDate alloc] init];
NSLog(#"now is %#", now);
[datepick setDate:now animated:YES];
[now release];
datepick.minimumDate = now;
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setHour:48];
NSDate *targetDate = [gregorian dateByAddingComponents:dateComponents toDate:todaysDate options:0];
[dateComponents release];
[gregorian release];
datepick.maximumDate = targetDate;
NSLog(#"targetDate is %#", targetDate);
}
This is default behavior when you set a minimum date and a maximum date and APPLE does it clearly to make it obvious that they are not selectable.
What you can do is implement a UIPickerView for the dates and implement viewForRow for the pickerView methods.
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
UILabel* tView = (UILabel*)view;
if (!tView){
tView = [[UILabel alloc] init];
// Add label.text which is the picker value for the row (for that component)
// set the font for the label as black.
}
You can also change the font size of the values in the pickerView.

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];
}

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

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
}