Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

Issue related to textfield and datepicker

I have an issue related to hide and show the datepicker view when click on textfield...Actually I have 2 textfields..Here is my problem image...

Problem

datepicker show and hide when click on textfiled...it should show on begin editing and hide on end editing...

enter image description here

At 1st time when we click on "textfield 1" its working good, but as soon as it resignFirstResponder and make 2nd field to respond, the problem occurs.

CODE

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    self.datepicker.alpha = 0.0
    self.datepicker.hidden = false
    UIView.animateWithDuration(0.3, animations: { () -> Void in
        self.datepicker.alpha = 1.0
        self.conDateHeight.constant = 100.0
        self.datepicker.addTarget(self, action: Selector("dataPickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)
    })
    return true
}

func textFieldShouldEndEditing(textField: UITextField) -> Bool {
        UIView.animateWithDuration(0.3, animations: {
        self.datepicker.alpha = 0.0
        }, completion: {
            (value: Bool) in
            self.conDateHeight.constant = 0.0
            self.datepicker.hidden = true
        })
    return true
}


func textFieldShouldReturn(textField: UITextField) -> Bool {
    if textField == self.txtToDate {
        txtToDate.resignFirstResponder()
        txtFromDate.becomeFirstResponder()
    }
    else if textField == self.txtFromDate {
        txtFromDate.resignFirstResponder()
        txtToDate.becomeFirstResponder()
    }
    return true
}  

When I hide keyboard after 1st textfield and then enter in second textfield its ok...otherwise the problem is as it is

Upvotes: 1

Views: 611

Answers (1)

Ashish Kakkad
Ashish Kakkad

Reputation: 23882

Batter to use date picker as input view

UIView *viewDateInput = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 200)];
[viewDateInput setBackgroundColor:[UIColor whiteColor]];
self.pickerDate = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, viewDateInput.frame.size.width, viewDateInput.frame.size.height)];
self.pickerDate.datePickerMode = UIDatePickerModeDate;
[viewDateInput addSubview:self.pickerDate];
[self.pickerDate addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
[self.txtDate setInputView:viewDateInput];

Function For date Change

- (void)dateChanged:(id)sender
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentTime = [dateFormatter stringFromDate:self.pickerDate.date];
self.txtDate.text = currentTime;
}

Upvotes: 1

Related Questions