Using Same UIDatePicker For Two TextFields
ios, objective-c, uidatepicker, uitextfield, xcode
Solution
You could implement the `UITextFieldDelegate` Protocol for both your TextFields `textFieldDidBeginEditing:` Method along with setting the `tag` property for each TextField so they are easily identifiable...
Then when `textFieldDidBeginEditing:` is called, you could read the tag of the textfield that has begun editing and set that as a global value so you can find out what textfield the date picker should change.. example:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
someGlobalNSInteger = textField.tag; //the current text field tag is now globally set
}
-(IBAction)dateValueChanged:(id)sender {
UIDatePicker *picker = (UIDatePicker *)sender;
NSDate *dateSelected1 = [picker date];
//NSDate *dateSelected1 = [picker date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
//self.fromTextField.text = [dateFormatter stringFromDate:dateSelected1];
//self.toTextField.text = [dateFormatter stringFromDate:dateSelected2];
UITextField *activeTextField = (UITextField*)[self viewWithTag:someGlobalNSInteger]; //gets text field what is currently being edited
[activeTextField setText:[dateFormatter stringFromDate:dateSelected1]];
}
However if you're not allowing the text field to be editable (so it can't bring the keyboard up) you may need some other way of figuring out what textField should get the updated date but i'll leave that to you.
Hope it helps
Problem
i am having two textfields,fromdate and todate.how to get different dates from the same datepicker.i tried something which ended up in getting the same date in both the textfields when the date is changed. ``` -(IBAction)dateValueChanged:(id)sender { UIDatePicker *picker = (UIDatePicker *)sender; NSDate *dateSelected1 = [picker date]; NSDate *dateSelected2 = [picker date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd-MM-yyyy"]; self.fromTextField.text = [dateFormatter stringFromDate:dateSelected1]; self.toTextField.text = [dateFormatter stringFromDate:dateSelected2]; } ```