Search code examples
objective-cuitableviewuitextfielduidatepickercustom-cell

UIDatePicker Replaces Keyboard only on Last Uitableviewcell


I have a tableview where a user can add a new row that contains two UITextFields in them. The user can add a date to each textview (or not add one, leaving it empty) with a UIDatePicker. Once the process is completed and everything is saved, the user should be able to go to any row and update the dates in that row. The problem is that any row previous to the very last row created only shows the regular keyboard when it is time to edit. I can't seem to get the datepicker to show up except in the last saved row. Any thoughts on why this is happening?

Here is how I set up the datepicker:

-(void)showDatePicker{
    _datePicker = [[UIDatePicker alloc] init];

    UIToolbar *toolbar = [[UIToolbar alloc]init];
    [toolbar sizeToFit];

    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(done)];

    doneButton.tintColor = [UIColor whiteColor];

    UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    toolbar.translucent = YES;
    toolbar.barTintColor = [UIColor colorWithRed:8/255.0 green:46/255.0 blue:46/255.0 alpha:1];

    [toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft,doneButton ,nil]];

    [_readDateCell.startDateTextfield setInputAccessoryView:toolbar];
    [_readDateCell.finishDateTextfield setInputAccessoryView:toolbar];

    [_datePicker setDatePickerMode:UIDatePickerModeDate];

    [_readDateCell.startDateTextfield setInputView:_datePicker];
    [_readDateCell.finishDateTextfield setInputView:_datePicker];
}

The function is called in two places - when the textfield begins editing and when a new row is being created:

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    [self showDatePicker];
}

-(void)addNewRow {
    [self showDatePicker];
}

Solution

  • If you are setting input view for your text field then there is no need to call showDatePicker on didBeginEditing delegate method of UITextField.

    Then you need to add the datePicker code in your viewDidLoad method. And in cellForRowAtIndexPath you need to set the inputAccessory and inputView