how to pop up datePicker when text filed click and disappear when editing done

六眼飞鱼酱① 提交于 2019-12-03 13:22:16
Fire Fist

Ok. Here is some sample code for your requirement with animation.

- (void) showView
{
    [self.view addSubview:yourDatePickerView];
        yourDatePickerView.frame = CGRectMake(0, -250, 320, 50);
        [UIView animateWithDuration:1.0
                         animations:^{
                             yourDatePickerView.frame = CGRectMake(0, 152, 320, 260);
                         }];
}

And here is how to hide your DatePickerView

- (void) hideView
{
    [UIView animateWithDuration:0.5
                         animations:^{
                             yourDatePickerView.frame = CGRectMake(0, -250, 320, 50);
                         } completion:^(BOOL finished) {
                             [yourDatePickerView removeFromSuperview];
                         }];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if(textField == yourDateTextField)
    {
         [self showView];
         return NO; // preventing keyboard from showing
    }
    return YES;
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField == yourDateTextField)
    {
         [self hideView];
    }
}

That's all you need.

You should identify the textfield in the delegate method.

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if(textField == DATE_TEXT_FIELD)
    {
             //Display date picker
    }
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{

        if(textField == DATE_TEXT_FIELD)
        {
                 //Hide date picker
            }
}
  • Create one UIView reference which contains this date picker view.
  • Now assign this datePickerContainerView to textField.inputView property.
  • Then assign textfield.delegate to self and implement your textFieldShouldReturn method. In that method, write this lines

    [textField resignFirstResponder];

    return YES;

Now when you tap on that textfield, it will load datepicker view in place of default keyboard, as per inputview property settings.

Before doing the code for datePicker,make sure that you type the following line of code

    [textField resignFirstResponder];

As we know,keyboard is the default first responder of a textField.So you should resign it first and then code for picker otherwise the keyboard will pop up as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!