0

I’d like to show a custom date picker keyboard when tapping a Toolbar button (UIBarButtonItem).

For showing custom keyboards using a a UIResponder’s inputView seems to be the right choice. Unfortunatelly the UIBarButtonItem isn’t a subclass of UIResponder.

How can I have a UIBarButtonItem becomeFirstResponder and carry an inputView to show such a keyboard?

Bernd
  • 11,133
  • 11
  • 65
  • 98

3 Answers3

0

Why do you want to show keyboard when user taps on UIBarButtonItem? Suppose keyboard is shown on tap of UIBarButtonItem, what will happen when user types in something using keyboard? Which control is expected to receive key press events from keyboard?

Mousam
  • 63
  • 6
0

Instead of inputView approach, you can follow another approach to show datePicker on button click

Let showDatePicker is the method called on button click then

-(void)showDatePicker
    {

    UIDatePicker* picker = [[UIDatePicker alloc] init];
                        picker.autoresizingMask = UIViewAutoresizingFlexibleWidth;
                        picker.datePickerMode = UIDatePickerModeDate;

    [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];
                        [self.view addSubview:picker];
    }


-(void) dueDateChanged:(UIDatePicker *)sender {
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];

    //self.myLabel.text = [dateFormatter stringFromDate:[dueDatePickerView date]];
    NSLog(@"Picked the date %@", [dateFormatter stringFromDate:[sender date]]);
}

To remove the datePicker, you can use removeFromSuperView on either method called from another button click in your View or your custom toolbar done button.

Piyush Sharma
  • 1,891
  • 16
  • 23
  • I don't want replace the whole screen content to show the picker. It should only replace the keyboard view. Also I would really prefer not to re-built all the showing/hiding/resizing logic of the date picker view unless I really have to… – Bernd Oct 28 '15 at 13:20
0

I've accomplished this by creating a UITextField

let myPicker = UIPickerView()
lazy var pickerInputField: UITextField = {
  let field = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
  self.view.addsubview(field)
  field.delegate = self
  return field
}()

func barButtonItemTouched(sender: Any) {

  // dismiss the picker if it's showing
  if pickerInputField.isFirstResponder {
    pickerInputField.resignFirstResponder()
  }

  pickerInputField.inputView = myPicker
  pickerInputField.becomeFirstResponder() 
}
Fred Faust
  • 6,696
  • 4
  • 32
  • 55