Tag Archives: objective-c

Xcode: DatePicker instead of keyboard

If you would like to use DatePicker instead of default keyboard when you make tap on the textField you should write following code:

in the ViewContoller.m file add method

1
2
3
4
5
6
7
8
9
10
11
-(void)updateTextField:(id)sender
{
  if([_editStartDate isFirstResponder]){
    UIDatePicker *picker = (UIDatePicker*)_editStartDate.inputView;
    _editStartDate.text = [NSString stringWithFormat:@"%@",picker.date];
  }
  if([_editEndDate isFirstResponder]){
    UIDatePicker *picker = (UIDatePicker*)_editEndDate.inputView;
    _editEndDate.text = [NSString stringWithFormat:@"%@",picker.date];  
  }
}

where _editStartDate and _editEndDate are textFields
and in the default method of controller's implementation:

1
2
3
4
5
6
7
8
9
10
11
12
- (void)viewDidLoad
{
  UIDatePicker *datePicker = [[UIDatePicker alloc]init];

  [datePicker setDate:[NSDate date]];
  [datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
  [_editStartDate setInputView:datePicker];

  [datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
  [_editEndDate setInputView:datePicker];
...
}

Result:
DatePicker_textField