Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: UIDatePicker UIControlEventValueChanged only fired on second selection

Working with UIDatePickers for the first time. To start, I'm just trying to update a text field with whatever value is selected from the datePicker (set in count down mode).

It works, but only the second time that a user selects a time. My action, durationSelected() is only called the second time, so there are no problems updating the textField.

Here's how I configured the date picker in my storyboard:

enter image description here

enter image description here

Here's the action triggered on Value Changed:

from DetailViewController.m

- (IBAction)durationSelected:(UIDatePicker *)sender
{
    self.durationTextField.text = [NSString stringWithFormat:@"%f seconds", sender.countDownDuration];
}

I've tried setting a default value, which had no effect.

What's going on?

like image 374
corbin Avatar asked Oct 08 '13 15:10

corbin


3 Answers

I have seen a similar bug with the iOS 7.0.3 UIDatePicker when it is used in UIDatePickerModeCountDownTimer mode. The picker does not fire the target-action associated with the UIControlEventValueChanged event the first time the user changes the value by scrolling the wheels. It works fine for subsequent changes.

Below is an efficient workaround. Simply enclose the code that sets the initial value of the countDownDuration in a dispatch block to the main loop. Your target-action method will fire every time the wheels are rotated to a new value. This approach has almost no overhead and works quite well on an iPhone 4 and iPad 4.

dispatch_async(dispatch_get_main_queue(), ^{
    self.myDatePicker.countDownDuration = (NSTimeInterval) aNewDuration ;
});
like image 190
Positron Avatar answered Nov 18 '22 11:11

Positron


This seems to be a bug in the iOS 7 implementation of UIDatePicker. I'd suggest filing a radar on it.

Building on the iOS 6 SDK and running on an iOS 6 device will work, while running on an iOS 7 device will not.

You can fix it by adding this line of code to your - (void)viewDidLoad method

[self.datePicker setDate:[NSDate date] animated:YES];
like image 24
Evan Avatar answered Nov 18 '22 09:11

Evan


I'm not sure, it's an educated guess :

It might be that iOS is keeping track of value changes for the Date Picker only when they are caused by animating the wheel. So it sets the value on your first "roll" but only detects that has changed on the second.

As I said, I cannot be sure of the reason, but the fix should be simple: just set the staring date programmatically after the view loads using setDate: animated: :

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.picker setDate:[NSDate dateWithTimeIntervalSinceNow:0] animated:true ];   
}

It seems to be working for me.

like image 4
vinaut Avatar answered Nov 18 '22 11:11

vinaut