Xcode Saving UIDatepicker to be displayed in a label - iphone

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

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

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
}

Date Picker format problems

How do i solve the problem where i got 2011-07-21 15:55:01 +0000 , but the timing is off by 4 hr, how do i remove the +0000? And I want the format to be Eg. Friday 12 June 2011 1:30 PM
-(IBAction)addButton:(id)sender
{
NSDate *choice = [datepick date];
NSString *words = [[NSString alloc]initWithFormat:#"%#", choice];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Date Chosen
message:words
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
[words release];
label.text = words;
textfield.text = words;
}
- (void)viewDidLoad
{
NSDate *now = [[NSDate alloc] init];
[datepick setDate:now animated:YES];
[now release];
datepick.minimumDate = [NSDate date];
[super viewDidLoad];
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE dd MMMM yyyy h:mm a"];
NSString *words = [formatter stringFromDate:choise];
Here date formatter guide.

multiple uipickerview and uidatapicker

i have a view with many select like checkInDate, checkOutDate (uidatepicker)
and age, room(uipickerView)...
i want to use showActionSheet to display the different pickerview when click diffrent tableViewCell
but i got two problem:
the checkInDate and theCheckOutDate can not be show the second time if i use checkOutDate.date = nowDate;
how can i use multi pickerview in this view? it should not be multiple Components.
here is the main code:
- (void)viewDidLoad {
age = [[UIPickerView alloc] init];
age.showsSelectionIndicator = YES;
age.delegate = self;
NSArray *ageData = [[NSArray alloc] initWithObjects:#"1", #"2", #"3", nil];
self.pickerData = data;
//room = [[UIPickerView alloc] init];
//room.showsSelectionIndicator = YES;
//room.delegate = self;
//NSArray *roomData = [[NSArray alloc] initWithObjects:#"6", #"7", nil];
//self.pickerData = roomDate;
//check data
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *now = [NSDate date];
NSDate *nextDay = [gregorian dateByAddingComponents:components toDate:now options:0];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
formatter.dateFormat = #"yyyy-MM-dd";
checkInDateStr = [formatter stringFromDate:nextDay];
NSDate *dayAfterTom = [gregorian dateByAddingComponents:components toDate:nextDay options:0];
checkOutDateStr = [formatter stringFromDate:dayAfterTom];
checkInDate = [[UIDatePicker alloc] init];
checkInDate.tag = checkInDateTag;
[checkInDate setMinimumDate:now];
checkInDate.datePickerMode = UIDatePickerModeDate;
//checkInDate.date = nextDay;
checkOutDate = [[UIDatePicker alloc] init];
checkOutDate.tag = checkOutDateTag;
[checkOutDate setMinimumDate:nextDay];
checkOutDate.datePickerMode = UIDatePickerModeDate;
//checkOutDate.date = dayAfterTom;
}
- (void)showActionSheet:(NSIndexPath *)indexPath withDataPickerTag:(NSInteger *)tag{
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:title delegate:self cancelButtonTitle:#"cancel" destructiveButtonTitle:nil otherButtonTitles:#"done", nil];
[actionSheet showInView:self.view];
//UIDatePicker *datePicker = [[[UIDatePicker alloc] init] autorelease];
// datePicker.tag = 101;
// datePicker.datePickerMode = UIDatePickerModeDate;
// NSDate *now = [NSDate date];
// [datePicker setDate:now animated:YES];
if (tag == 201){
[actionSheet addSubview:checkInDate];
}else if (tag == 202){
[actionSheet addSubview:checkOutDate];
}
}
#pragma mark -
#pragma mark Picker Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [pickerData count];
}
#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [pickerData objectAtIndex:row];
}
You can set the frame of a picker view.
Instead of
age = [[UIPickerView alloc] init];
Use
UIPickerView *picker = [[UIPickerView alloc] initWithFrame:<Your frame>];
or
[picker setFrame:<your frame>];
Using this you can use multiple picker views.
Keep an identifier to both so that you can handle the delegates.

NSDate - Change Time Component

This is probably a silly question but I can't seem to find an answer.
I am using a date picker to allow a user to enter a date and it is also setting the time to the current time (I init the picker with [NSDate date]).
Is there a way to change the time component of the date? I am later calculating time intervals which returns seconds and I am getting some odd behavior because of the time.
This code shows the date entry:
#implementation AddEventViewController
#synthesize backgroundColor, nameField, dateField, datePicker, eventName, eventDate;
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.view.backgroundColor = self.backgroundColor;
}
- (void)viewDidLoad
{
[super viewDidLoad];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
CGSize size = self.view.bounds.size;
CGRect frame = CGRectMake(0, size.height - 216, 320, 216);
datePicker = [[UIDatePicker alloc] initWithFrame: frame];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.hidden = YES;
datePicker.date = [NSDate date];
[datePicker addTarget:self
action:#selector(changeDateInLabel:)
forControlEvents:UIControlEventValueChanged];
[self.view addSubview: datePicker];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction)doneButton
{
if ((nameField.text != nil))
{
self.eventName = nameField.text;
self.eventDate = datePicker.date;
[[NSNotificationCenter defaultCenter]postNotificationName:#"EventAddDone" object:nil];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Enter Event Name" message:nil delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
-(IBAction)cancelButton
{
[[NSNotificationCenter defaultCenter]postNotificationName:#"EventAddCancel" object:nil];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)changeDateInLabel:(id)sender
{
dateField.text = [dateFormatter stringFromDate:[datePicker date]];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if(textField == dateField)
{
dateField.placeholder = #" ";
dateField.text = [dateFormatter stringFromDate:[datePicker date]];
datePicker.hidden = NO;
[nameField resignFirstResponder];
return NO;
}
return YES;
}
- (void)dealloc
{
self.backgroundColor = nil;
self.nameField = nil;
self.dateField = nil;
self.datePicker = nil;
self.eventName = nil;
self.eventDate = nil;
[dateFormatter release];
[super dealloc];
}
#end
My use of the recorded date is similar to the following:
NSTimeInterval age = [enteredDate timeIntervalSinceNow];
//do some math on the age variable to get number of days since the event occurred.
Two options:
Option 1:
int fromDate = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSEraCalendarUnit
forDate:enteredDate];
int toDate = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSEraCalendarUnit
forDate:[NSDate date]];
int days = toDate - fromDate;
option 2:
NSDate *dateA, *dateB;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
startDate:&dateA
interval:NULL
forDate:enteredDate];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
startDate:&dateB
interval:NULL
forDate:[NSDate date]];
//From here, apply the above method using components:fromDate:toDate:
//with dateA and dateB, which are set to the beginning of the days on
//which they lie.
NSInteger days = [[[NSCalendar currentCalendar] components:NSDayCalendarUnit
fromDate:enteredDate
toDate:[NSDate date]
options:0] day];