multiple uipickerview and uidatapicker - iphone

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.

Related

UIAlertView button is disabled even after picking date from UIDatePicker in iOS 7

The problem is that after picking date from UIDatePicker the "Ok" button of UIAlertView is disabled.I tried ,but no luck.
-(BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
should be called whenever we type anything in textfield,but when date is entered it's not getting called,but if i type anything from keyboard,its ok then.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section == 0 && indexPath.row == 1)
{
alertView1 = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Done",nil];
alertView1.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
alertView1.tag=1;
alertText = [alertView1 textFieldAtIndex:0];
itemText = [alertView1 textFieldAtIndex:1];
alertText.inputView=datePicker;
itemText.inputView=secondPicker;
[datePicker addTarget:self action:#selector(firstTF) forControlEvents:UIControlEventValueChanged];
[secondPicker addTarget:self action:#selector(secondTF) forControlEvents:UIControlEventValueChanged];
[alertText setPlaceholder:#"From Date"];
[itemText setPlaceholder:#"To Date"];
itemText.secureTextEntry = NO;
[alertView1 show];
}
- (void)firstTF
{
NSDate *date = datePicker.date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateStyle:NSDateFormatterMediumStyle];
alertText.text = [dateFormat stringFromDate:date];
}
- (void)secondTF
{
NSDate *date = secondPicker.date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateStyle:NSDateFormatterMediumStyle];
itemText.text = [dateFormat stringFromDate:date];
}
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if( [inputText length] > 0)
{
NSLog(#"alertViewShouldEnableFirstOtherButton: was called!");
return YES;
}
else
{
return NO;
}
}
The problem is you are not calling it to validate again..After values get inserted you should write this line to call validation..
[alertText sendActionsForControlEvents:UIControlEventEditingChanged];
in this method of yours..
- (void)firstTF

Calendar API changing

http://code.google.com/p/scm-subversion/source/browse/trunk/iPhone/CalendarTest/?r=4#CalendarTest%253Fstate%253Dclosed
I am using the above mentioned Calendar API. In CalendarTestViewController.m class we are getting the date. Now I have declared a global variable nsstring type and I want to use that date into another new class by using global variable. I have tried this a number of times but unable to get the output. If anyone know how can I use the selected date by using Calendar API, then please give me some solution.
Thanks in advance.
CODE
- (void)calendarView:(KLCalendarView *)calendarView tappedTile:(KLTile *)aTile{
NSLog(#"Date Selected is %#",[aTile date]);
str=(NSString *)[aTile date];
}
NSLog(#"str:%#",str);
glbdate1 = (NSString *)[aTile date];
NSLog(#"glbdate1:%#",glbdate1);
}
//I have declared the glbdate1 variable globally in app delegate file and i have made the new class calenderview
//I want to display the date in textfield by using global variable. Here is code in calenderview
-(void)viewWillAppear:(BOOL)animated {
if ([glbdate1 length] != 0)
{
from.text = glbdate1;
}
}
You have to convert the NSDate to NSString as follows,
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-mm-dd HH:mm:ss"];
NSString *dateString=[dateFormatter stringFromDate:date];
Then the same NSString value can be converted to NSDate as,
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-mm-dd HH:mm:ss"];
NSDate *dateFromString=[dateFormatter dateFromString:dateString];
-(BOOL)isDateinEventArray:(NSString*)iDateString{
//NSString *searchText = lblDate.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (ToDo *todoObj in appDelegate.todoArray)
{
NSString *date = todoObj.startDate;
[searchArray addObject:date];
}
if ([searchArray count] > 0) {
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:iDateString
options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
if ([copyListOfItems count] > 0) {
return TRUE;
}else{
return FALSE;
}
}
/*----- Calendar Delegates -----> */
- (void)calendarView:(KLCalendarView *)calendarView tappedTile:(KLTile *)aTile{
NSLog(#"Date Selected is %#",[aTile date]);
// NSString *stringFromDate =
// [[NSString alloc]initWithString:[NSString stringWithFormat:#"%02i-%02i-%i",[aTile.date dayOfMonth],
//
[aTile.date monthOfYear],[aTile.date yearOfCommonEra]]];
NSString *stringFromDate = [[NSString alloc]initWithString:[NSString stringWithFormat:#"%02i-%02i-%02i",[aTile.date yearOfCommonEra],
[aTile.date monthOfYear],[aTile.date dayOfMonth]]];
if([self isDateinEventArray:stringFromDate]){
selectedDate = [aTile date];
eventFoundMsg = #"Events are found on this date.";
eventMsgTag = 1;
}else{
eventFoundMsg = #"No events are found on this date.";
eventMsgTag = 0;
}
[stringFromDate release];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Event Message"
message:eventFoundMsg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil]autorelease];
alert.tag = eventMsgTag;
[alert show];
[aTile flash];
/*
if(tile == nil)
tile = aTile;
else
[tile restoreBackgroundColor];
*/
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (eventMsgTag == 1) {
if (buttonIndex == 0)
{
MyToDoView *detailViewController = [[MyToDoView alloc]
initWithNibName:#"MyToDoView" bundle:nil];
detailViewController.searchDate = selectedDate;
NSLog([NSString stringWithFormat:#"%#",detailViewController.searchDate]);
[detailViewController searchDateTableView];
[self.navigationController popViewControllerAnimated:YES];
[detailViewController release];
}
}
}
I hope this can help you....

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

Adding a button to UIDatePicker

Is it possible to add a 'Done' button to a UIDatePickerView,so that users can tap it to dismiss the view.
You should create a UIView to hold the picker and the button you need, then animate that view into the visible screen when you need a date entered, animate it away when the button is tapped. I have used a scheme like this where the button is actually the date label and is tapped to begin or end date editing.
I am Posting the code Please declare the objects that are undeclared as per their type Rest you will get it done.. Hope this helps...
#pragma mark DatePickerView
UIImagePickerController* imagePickerController;
UIDatePicker *theDatePicker;
UIToolbar* pickerToolbar;
UIActionSheet* pickerViewDate;
-(void)DatePickerView
{
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 = UIDatePickerModeDate;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]autorelease]];
[dateFormatter setDateFormat:#"dd MMM yyyy"];
//[dateFormatter setDateFormat:#"MM/dd/YYYY"];
//[theDatePicker release];
[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];
[pickerToolbar setItems:barItems animated:YES];
[pickerViewDate addSubview:pickerToolbar];
[pickerViewDate addSubview:theDatePicker];
[pickerViewDate showInView:self.view];
[pickerViewDate setBounds:CGRectMake(0,0,320, 464)];
}
-(IBAction)dateChanged{
NSDateFormatter *FormatDate = [[NSDateFormatter alloc] init];
[FormatDate setLocale: [[[NSLocale alloc]
initWithLocaleIdentifier:#"en_US"] autorelease]];
[FormatDate setDateFormat:#"MM/dd/YYYY"];
SelectedTextField.text = [FormatDate stringFromDate:[theDatePicker date]];
}
-(BOOL)closeDatePicker:(id)sender{
[pickerViewDate dismissWithClickedButtonIndex:0 animated:YES];
[pickerToolbar release];
[pickerViewDate release];
[SelectedTextField resignFirstResponder];
return YES;
}
-(IBAction)DatePickerDoneClick{
[self closeDatePicker:self];
tableview.frame=CGRectMake(0, 44, 320, 416);
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
// returns the number of rows
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return 30;
// return [pickerViewArray count];
}
Do the changes as per requirement. This is 100% running code almost used by me in similar application
hAPPY cODING...
This is a demo project for UIDatePicker with Cancel/Done buttons: https://github.com/lenhhoxung86/CustomDatePicker
One more customisable UIToolbar and UIDatePicker project. Might be helpful:
https://github.com/anatoliyv/SMDatePicker

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