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];
Related
In my Iphone app to create remainder, in the UIDate picker, the current time is not returned in default.Here my code is please help me.
MY viewController.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
UIBarButtonItem *add = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(addRemainder)];
self.navigationItem.rightBarButtonItem=add;
//TextField1...............................................................................................................
self.title=#"Add Remainder";
textField1 = [[UITextField alloc]initWithFrame:CGRectMake(20, 60, 280, 34)];
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField1.delegate = self;
textField1.placeholder = #"Enter the Reminder name";
[self.view addSubview:textField1];
//datePicker&TextField2....................................................................................................
datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0,210, self.view.frame.size.width, self.view.frame.size.height)];
[datePicker addTarget:self action:#selector(actionDone) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
//UserDefaults.............................................................................................................
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
remainder = [[NSMutableArray alloc]init];
TimeDate = [[NSMutableArray alloc]init];
if ([ud objectForKey:#"remainder"])
{
remainder = [[ud objectForKey:#"remainder"]mutableCopy];
TimeDate = [[ud objectForKey:#"TimeDate"]mutableCopy];
}
//to make the fields visible when we try to edit it............................................................................
if ([remainderr isEqualToString:#"edit"])
{
self.title = #"Reminder Edit";
textField1.text = [remainder objectAtIndex:[index integerValue]];
str = [TimeDate objectAtIndex:[index integerValue]];
}
}
#pragma mark - doneClicked
//DoneButton.................................................................................................................
-(void)actionDone
{
date = datePicker.date;
NSDateFormatter *dateform=[[NSDateFormatter alloc]init];
[datePicker setDate:[NSDate date]];
dateform.dateFormat = #"dd-MM-YYYY HH:mm:SS";
str=[dateform stringFromDate:date];
}
#pragma mark - AddRemainder Notifications
//addButton.................................................................................................................
-(void)addRemainder
{
//LocalNotification.........................................................................................................
notification = [[UILocalNotification alloc] init];
notification.fireDate = date;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
//NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
if ([remainderr isEqualToString:#"edit"])
{
[remainder replaceObjectAtIndex:[index integerValue] withObject:textField1.text];
[TimeDate replaceObjectAtIndex:[index integerValue] withObject: str];
[self.navigationController popViewControllerAnimated:YES];
}
else if([remainderr isEqualToString:#"delete"])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
else
{
if((textField1.text!=NULL)&&( date!=NULL))
{
[remainder addObject:textField1.text];
[TimeDate addObject: str];
[self.navigationController popViewControllerAnimated:YES];
}
else
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"Alert !" message:#"Please Give a title for your Remainder " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
}
}
//Adding objects............................................................................................................
//NSLog(#"%# %#", remainder, TimeDate);
[self.delegate store:remainder :TimeDate];
NSLog(#"The notifications is \n %#",notification);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#end
Thank you
Make your VoidAction as follows,
-(void)actionDone
{
NSDateFormatter *dateform=[[NSDateFormatter alloc]init];
dateform.dateFormat = #"dd-MM-yyyy HH:mm";
NSString *formattedDate = [dateform stringFromDate:datePicker.date];
date=[dateform dateFromString:formattedDate];
str=[dateform stringFromDate:date];
}
Note: Be relevant when you post questions. Thank you.
I have made an app which is an Customized Alarm App. The UILocalNotification should invoke at the time selected by me in UIDatePicker, but is is not invoking at correct timing. For example, I selected the time as 2:00PM for the alarm, so the notification will invoke between 2:00PM and 2:01PM... but not sure when... it is giving me a delay of random time. In my UITableView you can see that it is the description displayed is also comes wrong. I know I am from India so it showing GMT timings, but can it could be corrected?
Here is my whole code:-
-----------------------------AppDelegate.m File :------------------------------
#synthesize window,viewController,timeViewController;
NSString *kRemindMeNotificationDataKey = #"kRemindMeNotificationDataKey";
#pragma mark -
#pragma mark === Application Delegate Methods ===
#pragma mark -
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
int x = [[NSUserDefaults standardUserDefaults] integerForKey:#"Mayank"];
if( x == 1 )
{
timeViewController = [[TimeViewController alloc]initWithNibName:#"TimeViewController" bundle:nil];
timeViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
CGRect frame = timeViewController.view.frame;
frame.origin = CGPointMake(frame.origin.x,frame.origin.y + statusBarFrame.size.height );
timeViewController.view.frame = frame;
[self.window addSubview:timeViewController.view];
}
else
{
[[NSUserDefaults standardUserDefaults]setInteger:1 forKey:#"Mayank"];
[[NSUserDefaults standardUserDefaults]synchronize];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Do you want to set the Default Alarm?" message:#"at 4:20 PM" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok",nil];
[alert show];
[alert release];
}
sleep(1);
[self.window makeKeyAndVisible];
application.applicationIconBadgeNumber = 0;
// Handle launching from a notification
UILocalNotification *localNotification =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification) {
NSString *reminderText = [localNotification.userInfo
objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
}
return YES;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)
{
timeViewController = [[TimeViewController alloc]initWithNibName:#"TimeViewController" bundle:nil];
timeViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
CGRect frame = timeViewController.view.frame;
frame.origin = CGPointMake(frame.origin.x,frame.origin.y + statusBarFrame.size.height );
timeViewController.view.frame = frame;
[self.window addSubview:timeViewController.view];
}
if(buttonIndex == 1)
{
viewController = [[SetAlarmViewController alloc]initWithNibName:#"SetAlarmViewController" bundle:nil];
viewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
CGRect frame = viewController.view.frame;
frame.origin = CGPointMake(frame.origin.x,frame.origin.y + statusBarFrame.size.height );
viewController.view.frame = frame;
[self.window addSubview:viewController.view];
}
}
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
application.applicationIconBadgeNumber = 0;
}
-----------------------------mainViewController.m File :------------------------------
#implementation SetAlarmViewController
#synthesize datePicker,tableview, eventText,titleBar,setAlarmButton,returnKeyType;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (The420DudeAppDelegate *)[[UIApplication sharedApplication] delegate];
eventText.returnKeyType = UIReturnKeyDone;
// datePicker.minimumDate = [NSDate date];
NSDate *now = [NSDate date];
[datePicker setDate:now animated:YES];
eventText.delegate = self;
index = 0;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
[self.tableview reloadData];
}
- (IBAction) scheduleAlarm:(id) sender {
[eventText resignFirstResponder];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = pickerDate;
// NSLog(#"%#",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// NSLog(#"%#",localNotif.timeZone);
// Notification details
localNotif.alertBody = [eventText text];
// Set the action button
localNotif.alertAction = #"Show me";
localNotif.repeatInterval = NSDayCalendarUnit;
localNotif.soundName = #"jet.wav";
// Specify custom data for the notification
NSDictionary *userDict = [NSDictionary dictionaryWithObject:eventText.text
forKey:kRemindMeNotificationDataKey];
localNotif.userInfo = userDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
[self.tableview reloadData];
eventText.text = #"";
viewController = [[TimeViewController alloc] initWithNibName:#"TimeViewController" bundle:nil];
[self presentModalViewController:viewController animated:YES];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
index = indexPath.row;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Warning!!!"
message:#"Are you sure you want to Delete???" delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok",nil];
[alertView show];
[alertView release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notify = [notificationArray objectAtIndex:index];
if(buttonIndex == 0)
{
// Do Nothing on Tapping Cancel...
}
if(buttonIndex ==1)
{
if(notify)
[[UIApplication sharedApplication] cancelLocalNotification:notify];
}
[self.tableview reloadData];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
[cell.textLabel setText:notif.alertBody];
[cell.detailTextLabel setText:[notif.fireDate description]];
return cell;
}
- (void)showReminder:(NSString *)text {
/*
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Reminder"
message:#"hello" delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[self.tableview reloadData];
[alertView release];
*/
NSString *path = [[NSBundle mainBundle]pathForResource:#"jet" ofType:#"wav"];
NSURL *url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
player.numberOfLoops = -1;
[player play];
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
[actionSheet showInView:self.view];
// [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
[player stop];
if(buttonIndex == 0)
{
NSLog(#"OK Tapped");
}
if(buttonIndex == 1)
{
NSLog(#"Cancel Tapped");
}
}
This Pic Shows My App View :
NSDate *pickerDate = [self.pickerTime date];
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:pickerDate];
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
**[dateComps setSecond:00];**
NSDate *itemDate = [calendar dateFromComponents:dateComps];
localNotification.fireDate = itemDate;
just keep in mind, the date from datepicker comes aligned with GMT. you have to convert to your own timezone by yourself. this could be the issue in your case.
I think the problem here has to do with the NSDatePicker returning the seconds of the current time along with the selected time. You need to strip the seconds from the date returned by the NSDatePicker and use that for your alarm and local notification.
NSDate *selectedDate = [datePicker date]; // you don't need to alloc-init the variable first
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *dc = [cal components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:selectedDate];
selectedDate = [cal dateFromComponents:dc];
// now you have an NSDate with zero seconds for your alarm
You should get much better accuracy on your notifications, but I don't think they're guaranteed to be exactly on the split second.
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..
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];
}
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.