SpokaneDude
SpokaneDude

Reputation: 4974

Why do I have to tap UIDatePicker twice to set time?

I have a UIDatePicker that I want to set to the string value in a textField. When I tap a second textField, I want the UIDatePicker to take the value in the first textField and use it as the starting time in the datePicker.

This works correctly, but only when I tap the second textField two times. The first time I tap it, the text field is selected (turns yellow) and the time is set to 6:00 am every time! When I tap the textField again, the timePicker is set correctly...

This is the result of tapping once:

enter image description here

This is the result of the second tap:

enter image description here

UPDATE: This is the code implemented for the tap:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

[textField resignFirstResponder];   //  don't display the k/b

if (textField.tag == kStartTimeTag)  {
    textFieldTag = kStartTimeTag;
    textField.backgroundColor = [UIColor colorWithRed:252.0/255.0 green:255.0/255.0 blue:197.0/255.0 alpha:1.0];
}
else if (textField.tag == kEndTimeTag)  {
    textField.backgroundColor = [UIColor colorWithRed:252.0/255.0 green:255.0/255.0 blue:197.0/255.0 alpha:1.0];    
    textFieldTag = kEndTimeTag;

    //  now, set end time equal to start time
    [self.oTimePicker setDate:dateFromString(oStartTime.text, @"HH:mm")];

}

return NO;

}

Is there a way to make this work on the first tap?

Upvotes: 2

Views: 286

Answers (2)

SpokaneDude
SpokaneDude

Reputation: 4974

Here's the solution for anybody who needs to do what I needed done:

    [self.oTimePicker setDate:dateFromString(self.oStartTime.text, @"HH:mm")];
    [self.oTimePicker reloadInputViews];

The key is the second line: -reloadInputViews

Thank you everybody for your suggestions...

Upvotes: 1

rdelmar
rdelmar

Reputation: 104082

I'm not sure what's wrong with your code, since you don't show what you're doing in the function dateFromString(). The code below worked for me on a single tap:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    [textField resignFirstResponder];   //  don't display the k/b

    if (textField.tag == 1)  {
        textField.backgroundColor = [UIColor colorWithRed:252.0/255.0 green:255.0/255.0 blue:197.0/255.0 alpha:1.0];
    }
    else if (textField.tag == 2)  {
        textField.backgroundColor = [UIColor colorWithRed:252.0/255.0 green:255.0/255.0 blue:197.0/255.0 alpha:1.0];
        NSDate *startDate = [self timeFromString:self.oStartTime.text];
        [self.oTimePicker setDate:startDate];
    }
    return NO;
}

-(NSDate *)timeFromString:(NSString *)  timeString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm";
    return [formatter dateFromString:timeString];
}

Upvotes: 1

Related Questions