iPhone datepicker instead of keyboard? - iphone

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

Related

IOS actionsheet button selection not working properly

Hi I am developing small IOS application in which I am using actionsheet. So my problem is like this when I clicked outside the actionsheet it is closing my actionsheet it is calling - (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex method even though I am not clicking any button of actionsheet. It is returning lastindexof action sheet button. So how to avoid this. Any solution? I tried with -(void)actionSheet:(UIActionSheet *)action didDismissWithButtonIndex:(NSInteger)buttonIndex
But still same result.
I write the time picker by my self instead UIActionSheet in iOS8:
date = [NSDate date];
timePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];
timePicker.datePickerMode = UIDatePickerModeDateAndTime;
timePicker.hidden = NO;
timePicker.date = date;
displayFormatter = [[NSDateFormatter alloc] init];
[displayFormatter setTimeZone:[NSTimeZone localTimeZone]];
[displayFormatter setDateFormat:#"MM月dd日 EEE HH:mm"];
formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
[formatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
startDisplayTimeString = [displayFormatter stringFromDate:timePicker.date];
startTimeString = [formatter stringFromDate:timePicker.date];
NSTimeInterval interval = 24*60*60*1;
NSDate *endDate = [[NSDate alloc] initWithTimeIntervalSinceNow:interval];
endDisplayTimeString = [displayFormatter stringFromDate:endDate];
endTimeString = [formatter stringFromDate:endDate];
[_startTimeLabel setText:startDisplayTimeString];
[_endTimeLabel setText:endDisplayTimeString];
[pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
pickerToolbar.tintColor = [UIColor whiteColor];
[pickerToolbar sizeToFit];
UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:#"Cancel" style:UIBarButtonItemStyleBordered target:self action:#selector(cancelBtnPressed:)];
[cancelBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:253.0/255.0 green:68.0/255.0 blue:142.0/255.0 alpha:1.0],
NSForegroundColorAttributeName,
nil] forState:UIControlStateNormal];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *titleButton;
float pickerMarginHeight = 168;
titleButton = [[UIBarButtonItem alloc] initWithTitle:#"title" style:UIBarButtonItemStylePlain target: nil action: nil];
[titleButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:253.0/255.0 green:68.0/255.0 blue:142.0/255.0 alpha:1.0],
NSForegroundColorAttributeName,
nil] forState:UIControlStateNormal];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:#"OK" style:UIBarButtonItemStyleDone target:self action:#selector(setTimePicker)];
[doneBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:253.0/255.0 green:68.0/255.0 blue:142.0/255.0 alpha:1.0],
NSForegroundColorAttributeName,
nil] forState:UIControlStateNormal];
NSArray *itemArray = [[NSArray alloc] initWithObjects:cancelBtn, flexSpace, titleButton, flexSpace, doneBtn, nil];
[pickerToolbar setItems:itemArray animated:YES];
if(iPad){
[pickerToolbar setFrame:CGRectMake(0, 0, 320, 44)];
UIViewController* popoverContent = [[UIViewController alloc] init];
popoverContent.preferredContentSize = CGSizeMake(320, 216);
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];
popoverView.backgroundColor = [UIColor whiteColor];
[popoverView addSubview:timePicker];
[popoverView addSubview:pickerToolbar];
popoverContent.view = popoverView;
popoverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
[popoverController presentPopoverFromRect:CGRectMake(0, pickerMarginHeight, 320, 216) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}else{
timeBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-300, 320, 246)];
[timeBackgroundView setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0]];
[timeBackgroundView addSubview:pickerToolbar];
[timeBackgroundView addSubview:timePicker];
[self.view addSubview:timeBackgroundView];}
When you tap outside of the UIActionSheet, UIKit performs the same action as if you had tapped the cancel button. The buttonIndex that is sent in - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex is the cancel button index. There isn't a way to know if the user tapped outside of your UIActionSheet, by default. If you want this functionality you will have to code your own custom action sheet or handle the outside tap as a cancel tap.

how can i go back after selecting date in date picker

I am facing a problem in date picker. when am i clicking on date picker done button. then my code is crashing.
-(IBAction)btn:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
datelabel.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:[NSDate date]]];
[df release];
[self.view addSubview:datelabel];
[datelabel 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;
datelabel.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:datePicker.date]];
}
UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.barStyle = UIBarStyleBlackOpaque;
toolbar.frame=CGRectMake(0,4,datePicker.frame.size.width,40);
[datePicker addSubview:toolbar];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleBordered target:self action:#selector(DoneSelected)];
[toolbar setItems:[NSArray arrayWithObjects:flexibleSpace,doneBtn,nil]];
[flexibleSpace release];
}
-(void)DoneSelected
{
your implementation code
}

how to set label to center in uitoolbar

I am developing an universal app for iOS so that I have to set label to center in UIToolBar. Please help me to do this.
The code I have implemented
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 250, 40)];
label.backgroundColor = [UIColor clearColor];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:label];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"dd-MM-yyyy hh:mm a"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
label.text = dateString;
FirstViewController.h
#interface FirstViewController:UIVieWController
{
UILable *justLabel;
}
#end
In FirstViewController.m try The fallowing code .Here I am taking timer for displaying time on the UIToolbar
#implementation FirstViewController
-(void)viewDidLoad
{
UIToolbar *tool=[[UIToolbar alloc] initWithFrame:CGRectMake(0,372, self.view.frame.size.width, 44)];
justLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 4, 250, 40)];
justLabel.backgroundColor = [UIColor clearColor];
[self.view addSubview:tool];
[tool addSubview:justLabel];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(timer) userInfo:nil repeats:YES];
}
-(void)timer
{
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"dd-MM-yyyy hh:mm:ss a"];
NSDate *now = [NSDate date];
NSString *dateString = [format stringFromDate:now];
justLabel.text=dateString;
}
#end
You have to add flexible space bar button items before and after the label, this will center the label in your toolbar.
The flexible space is one of the system items when creating UIBarButtonItems. When you set the items of your toolbar, it should be an array containing a flexible space, your label, and another flexible space.
Set frame of label according to the view width....
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width-250)/2, 0, 250, 40)];
here in (self.view.frame.size.width-250)/2 250 is your required label width.....
By setting page with i am
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, (self.view.frame.size.width)-55, 20)];

pickerview selectedRowInComponent always returning 0

I am using selectedRowInComponent method to get the presently selected row on component with index 0 but it is always returning 0. I have checked it in
NSLog("%d",[pickerview selectedRowInComponent:0]);
I have initialized the picker as I am using picker view programmatically. Please Suggest.
I hope this code will help you.I am using it in my project its working perfect.
Call this function it ViewDidLoad
[self loadFirstPicker];
Below is function to make UIpicker which shows only time. (And Save in text feild)
-(void)loadFirstPicker
{
UIDatePicker *picker = [[UIDatePicker alloc] init];
picker.autoresizingMask = UIViewAutoresizingFlexibleWidth;
picker.datePickerMode = UIDatePickerModeTime;
[picker addTarget:self action:#selector(dueDateChanged:) forControlEvents:UIControlEventValueChanged];
CGSize pickerSize = [picker sizeThatFits:CGSizeZero];
picker.frame = CGRectMake(0.0, 250, pickerSize.width, 460);
picker.backgroundColor = [UIColor blackColor];
checkEveryTextFeild.inputView = picker;
//[self.view addSubview:picker];
//[picker release];
// Create done button in UIPickerView
UIToolbar* mypickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 220, 56)];
mypickerToolbar.barStyle = UIBarStyleBlackOpaque;
[mypickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(pickerDoneClicked)];
[barItems addObject:doneBtn];
[mypickerToolbar setItems:barItems animated:YES];
checkEveryTextFeild.inputAccessoryView = mypickerToolbar;
}
This Function getting the time from picker and setting it to textFeild
-(void) dueDateChanged:(UIDatePicker *)sender {
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH:mm:ss"];
//[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
checkEveryTextFeild.text = [dateFormatter stringFromDate:[sender date]];
NSDate *currentDate = [NSDate date];
NSLog(#"%#",currentDate);
NSLog(#"Picked the date %#", [dateFormatter stringFromDate:[sender date]]);
}
you might want to try setting both of them. the second line will retrieve the pickerview that the class detects:
[filterPicker selectRow:selectedPickerIndex inComponent:0 animated:NO];
[self pickerView:filterPicker didSelectRow:selectedPickerIndex inComponent:0];
self.personInfoPicker.delegate = self;
self.personInfoPicker.dataSource = self;
[self.personInfoPicker reloadAllComponents];

Problem in Datepicker and alertsheet

I am implementing UIDATEPICKER. The problem is that when i click on the button, The alert sheet is appear and datepicker is add as subview but i want two button,
1-cancel 2-done
what will i do?
UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:#"How many?"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
aac.actionSheetStyle = UIActionSheetStyleBlackOpaque;
sheet = aac;
UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
if(IsDateSelected==YES)
{
theDatePicker.datePickerMode = UIDatePickerModeDate;
theDatePicker.maximumDate=[NSDate date];
}else {
theDatePicker.datePickerMode = UIDatePickerModeTime;
}
self.dtpicker = theDatePicker;
[theDatePicker release];
[dtpicker addTarget:self action:#selector(dateChanged) forControlEvents:UIControlEventValueChanged];
pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerDateToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(DatePickerCancelClick)];
[barItems addObject:cancelBtn];
////
it doesnot work ..I want this....
what will i do?
-(IBAction)DatePickerView
{
iRolegameAppDelegate *appDelegate = (iRolegameAppDelegate *)[[UIApplication sharedApplication]delegate];
pickerViewDate = [[UIActionSheet alloc] initWithTitle:#"How many?"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
theDatePicker.datePickerMode = UIDatePickerModeDateAndTime;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]autorelease]];
[dateFormatter setDateFormat:#"MM/dd/YY h:mm a"];
[theDatePicker addTarget:self action:#selector(dateChanged) forControlEvents:UIControlEventValueChanged];
pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerToolbar.barStyle=UIBarStyleBlackOpaque;
[pickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(DatePickerDoneClick)];
[barItems addObject:flexSpace];
UIBarButtonItem *spacer = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
[barItems addObject:spacer];
UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(DatePickerCancelClick)];
[barItems addObject:cancelBtn];
[pickerToolbar setItems:barItems animated:YES];
[pickerViewDate addSubview:pickerToolbar];
[pickerViewDate addSubview:theDatePicker];
[pickerViewDate showInView:self.view];
[pickerViewDate setBounds:CGRectMake(0,0,320, 464)];
NSDateFormatter *currentdateformate = [[NSDateFormatter alloc] init];
[currentdateformate setDateFormat:#"HH:MM, EEEE, dd-MMMM-yyyy"];
appDelegate.timestamp1 = [currentdateformate stringFromDate:[theDatePicker date]];
NSDateFormatter *currentdateformate1 = [[NSDateFormatter alloc] init];
[currentdateformate1 setDateFormat:#"MMM dd, yyyy HH:mm"];
self.updatedate = [currentdateformate1 stringFromDate:[theDatePicker date]];
}
-(IBAction)dateChanged{
iRolegameAppDelegate *appDelegate = (iRolegameAppDelegate *)[[UIApplication sharedApplication]delegate];
NSDateFormatter *currentdateformate = [[NSDateFormatter alloc] init];
[currentdateformate setDateFormat:#"HH:MM, EEEE, dd-MMMM-yyyy"];
appDelegate.timestamp1 = [currentdateformate stringFromDate:[theDatePicker date]];
NSLog(#"%#",appDelegate.timestamp1);
[currentdateformate setDateFormat:#"MMM dd, yyyy HH:mm"];
self.updatedate = [currentdateformate stringFromDate:[theDatePicker date]];
}
-(void)DatePickerCancelClick
{
self.pickerViewDate.hidden = YES;
self.view.hidden = NO;
[self.pickerViewDate dismissWithClickedButtonIndex:0 animated:YES];
}
-(BOOL)closeDatePicker:(id)sender{
//iRolegameAppDelegate *appDelegate = (iRolegameAppDelegate *)[[UIApplication sharedApplication]delegate];
[pickerViewDate dismissWithClickedButtonIndex:0 animated:YES];
[pickerToolbar release];
[pickerViewDate release];
//[SelectedTextField resignFirstResponder];
if([ self.updatedate isEqualToString:#"nil"]){
NSDateFormatter *currentdateformate = [[NSDateFormatter alloc] init];
[currentdateformate setDateFormat:#"MMM dd, yyyy HH:mm"];
self.updatedate = [currentdateformate stringFromDate:[theDatePicker date]];
[dateSelectButton setTitle:self.updatedate forState:UIControlStateNormal];
self.updatedate = #"";
}
else{
[dateSelectButton setTitle:self.updatedate forState:UIControlStateNormal];
self.updatedate = #"";
}
return YES;
}
-(IBAction)DatePickerDoneClick{
[self closeDatePicker:self];
}
maybe you should get rid of the UIActionSheet and do it like I did for another question.
UIDatePicker pop up after UIButton is pressed