Showing posts with label uidatepicker. Show all posts
Showing posts with label uidatepicker. Show all posts

Friday, July 14, 2017

How to change background color of UIDatePicker set as UITextField inputView?

Leave a Comment

Please do not mark as duplicate. The available answers haven't answered my issue.

I am using a UIDatePicker as UITextField's inputView (inside a UITableViewCell):

@IBOutlet weak var theTextField: UITextField!  func textFieldDidBeginEditing(_ textField: UITextField) {          let picker = UIDatePicker()         picker.setValue(Colors.CI2, forKeyPath: "textColor")          picker.datePickerMode = .date          textField.inputView = picker         textField.inputView?.backgroundColor = Colors.CI1 // my desired color          picker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)  } 

The problem: The color does only change, once the picker is called a second time.

enter image description here enter image description here

I guess, that this issue occurs because the inputView is optional and only once the picker is called a second time, the inputView is instantiated at the moment where I want to change the color.

I have tried to subclass UITextField and observe inputView.

class DateTextField: UITextField {      override var inputView: UIView? {          didSet {              self.inputView?.backgroundColor = Colors.CI1             self.reloadInputViews()          }      }  } 

Unfortunately without success. Same behavior. What am I missing? Help is very appreciated.

5 Answers

Answers 1

create a function which holds the date picker colours, and call it in the textFieldDidBeginEditing. I think that should solve your issue.

Answers 2

So you mention that this text field is within a UITableViewCell... What I would suggest is adding the first block of code to a UITextFieldDelegate and then in the tableView(_:willDisplay:forRowAt:) function in the UITableViewDelegate , set the delegate of the text field to your custom UITextFieldDelegate.

Without knowledge of more of your code structure I can only provide you with a very generic implementation:

@IBOutlet weak var theTextField: UITextField!  //Add your customisation to the textField... extension ViewController : UITextFieldDelegate {     func textFieldDidBeginEditing(_ textField: UITextField) {              let picker = UIDatePicker()             picker.setValue(Colors.CI2, forKeyPath: "textColor")              picker.datePickerMode = .date              textField.inputView = picker             textField.inputView?.backgroundColor = Colors.CI1 // my desired color              picker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)      } }  extension ViewController : UITableViewDelegate {     //Set the delegate when the UITableViewCell appears:     func tableView(_ tableView: UITableView,                  willDisplay cell: UITableViewCell,                     forRowAt indexPath: IndexPath) {         let dateCell = = self.tableView.dequeueReusableCellWithIdentifier("cell") as! DateCell          dateCell.delegate = self          return dateCell     } } 

Answers 3

Do not change inputView in textFieldDidBeginEditing(). The last time you can change the textField.inputView property is in textFieldShouldBeginEditing().

As for the best practice: you should move all the code for the textView.inputView configuration to the place where you create the textView to do a one time configuration. For instance:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {     // get the cell     // get your instance of textField     // ...      // Configure everything you want about your input view     let picker = UIDatePicker()     picker.setValue(Colors.CI2, forKeyPath: "textColor")     picker.datePickerMode = .date     picker.backgroundColor = Colors.CI1     textField.inputView = picker // <-- You just have to assign this ONCE      // ... Continue your setup ...     return cell } 

If you need to change the configuration of the inputView each time it has to appear on screen, do the change of textView.inputView = ... in textFieldShouldBeginEditing(){ ... }.


Why it did not work

In your code (when you do the change in textField DID BeginEditing), the UIDatePicker shown was always the previously created one. It seems that the gray one was set (but not configured) when you created the textField instance.

In textFieldDidBeginEditing(), the system has already drawn the textView.inputView and it will NOT look again at the inputView property if you modify it.

Answers 4

You could use the following library for custom colours https://github.com/prolificinteractive/PIDatePicker

Answers 5

This code is working for me

func textFieldDidBeginEditing(_ textField: UITextField) {            let picker = UIDatePicker()         picker.datePickerMode = .date          textField.inputView = picker         textField.inputView?.backgroundColor = UIColor.blue  } 

Screenshot

Even on the first edit it shows up blue.

Also:

Instead of creating a picker instance inside textField delegate method, you could create the picker in viewDidLoad method, set its background color, give it a tag and then access this picker using the tag in the delegate method instead of creating the variable there.

Read More

Wednesday, April 6, 2016

How to add a “Done” button with in the DatePicker Through StoryBoard?

Leave a Comment

In my app i want to display UIDatePicker when user click on button.and that date save into UITextFiled.I done this things. My problem is when date picker appears there is no done button,How can add that done button. Upto now i tried.

- (IBAction)pickerAction:(id)sender { datePicker.datePickerMode=UIDatePickerModeDate; datePicker.hidden=NO; datePicker.date=[NSDate date]; [datePicker addTarget:self action:@selector(TextTitle:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:datePicker]; NSDateFormatter * df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"M-d-yyyy"]; selectedDate.text=[df stringFromDate:datePicker.date]; }   -(void)TextTitle:(id)sender { NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"M-d-yyyy"]; selectedDate.text = [NSString stringWithFormat:@"%@",                       [df stringFromDate:datePicker.date]];  } 

How can i add done button with this code. please help me.

5 Answers

Answers 1

Answer is

datePicker=[[UIDatePicker alloc]init]; datePicker.datePickerMode=UIDatePickerModeDate; [TextField1 setInputView:datePicker];  UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)]; [toolBar setTintColor:[UIColor grayColor]]; UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(ShowSelectedDate)]; UIBarButtonItem *space=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; [toolBar setItems:[NSArray arrayWithObjects:space,doneBtn, nil]];  [TextField1 setInputAccessoryView:toolBar]; 

Answers 2

I added a UIToolbar with a UIBarButtonItem for the 'done' button in my xib with the frame set so that it's not initially visible (y value equal to the height of the parent view).

Every time the user access the picker, I changed the frame (the y value) of the UIDatePicker and the UIToolbar with an animation so that it slides up along with the picker from the bottom of the screen similar to the keyboard.

Check out my code below.

- (IBAction)showPicker {     if(pickerVisible == NO)     {         // create the picker and add it to the view         if(self.datePicker == nil) self.datePicker = [[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 460, 320, 216)] autorelease];         [self.datePicker setMaximumDate:[NSDate date]];         [self.datePicker setDatePickerMode:UIDatePickerModeDate];         [self.datePicker setHidden:NO];         [self.view addSubview:datePicker];          // the UIToolbar is referenced 'using self.datePickerToolbar'         [UIView beginAnimations:@"showDatepicker" context:nil];         // animate for 0.3 secs.         [UIView setAnimationDuration:0.3];          CGRect datepickerToolbarFrame = self.datePickerToolbar.frame;         datepickerToolbarFrame.origin.y -= (self.datePicker.frame.size.height + self.datePickerToolbar.frame.size.height);         self.datePickerToolbar.frame = datepickerToolbarFrame;          CGRect datepickerFrame = self.datePicker.frame;         datepickerFrame.origin.y -= (self.datePicker.frame.size.height + self.datePickerToolbar.frame.size.height);         self.datePicker.frame = datepickerFrame;          [UIView commitAnimations];         pickerVisible = YES;     } }  - (IBAction)done {     if(pickerVisible == YES)     {         [UIView beginAnimations:@"hideDatepicker" context:nil];         [UIView setAnimationDuration:0.3];          CGRect datepickerToolbarFrame = self.datePickerToolbar.frame;         datepickerToolbarFrame.origin.y += (self.datePicker.frame.size.height + self.datePickerToolbar.frame.size.height);         self.datePickerToolbar.frame = datepickerToolbarFrame;          CGRect datepickerFrame = self.datePicker.frame;         datepickerFrame.origin.y += (self.datePicker.frame.size.height + self.datePickerToolbar.frame.size.height);         self.datePicker.frame = datepickerFrame;         [UIView commitAnimations];          // remove the picker after the animation is finished         [self.datePicker performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.3];     } } 

Answers 3

go to the link below.

http://www.iostute.com/2015/01/create-and-use-date-picker-uidatepicker.html

i think it'll help you.

Answers 4

You can use UIView and in this UIView add your Datepicker and Done button. Done button create Action event and in this you will handle your UIView hide and show. Hope this helps

Answers 5

Check this library. It is very easy to implement.

https://github.com/hackiftekhar/IQActionSheetPickerView

Read More