Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when user taps the selection indicator in a UIDatePicker?

How can I detect when the user taps the selection indicator in a UIDatePicker?

Without this the user has to scroll to some other date and then back again to pick the date which is displayed under the selection indicator when the date picker slides up.

Thanks a lot,
Stine

The date picker is scrolled to current date when sliding up

UPDATE: This is the only solution I could come up with myself:

UIDatePicker *aDatePicker = [[UIDatePicker alloc] init];
self.datePicker = aDatePicker;
[aDatePicker release];
[self.datePicker addTarget:self action:@selector(datePicked:) forControlEvents:UIControlEventValueChanged];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(datePicked:)];    
[self.datePicker addGestureRecognizer:tap];
[tap release];

Which means that datePicked will be called twice when the user actually rotates the wheel.

UPDATE: The above mentioned solution does not work for UIPickerViews though. I do not know how to achieve the wanted behavior in those cases.

like image 271
Stine Avatar asked Feb 23 '23 23:02

Stine


2 Answers

You can do some tweak in this way:-

Conform delegate <UIGestureRecognizerDelegate>in your .h file

UITapGestureRecognizer* gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerViewTapGestureRecognized:)];
[yourDatePicker addGestureRecognizer:gestureRecognizer];
gestureRecognizer.delegate=self;
gestureRecognizer.numberOfTapsRequired=2;//Whenever you do double tap it will called. So allow user to do double tap on selected date.

//Below is the Delegate method

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

//Below method will trigger when do the double tap

-(void)pickerViewTapGestureRecognized:(UITapGestureRecognizer*)recognizer
{
   UIDatePicker *datePicker=(UIDatePicker*)[[recognizer view] viewWithTag:101];
   NSLog(@"datePicker=%@", datePicker.date);
 }
like image 165
Hussain Shabbir Avatar answered Apr 09 '23 02:04

Hussain Shabbir


Try this code:

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerViewTapped:)];

[recognizer setNumberOfTapsRequired:2];
[recognizer setCancelsTouchesInView:NO];
[recognizer setDelaysTouchesEnded:NO];
[recognizer setDelaysTouchesBegan:NO];

[self.answerPicker addGestureRecognizer:recognizer];

// ....

- (IBAction)pickerViewTapped:(UITapGestureRecognizer *)sender {
    CGPoint coord = [sender locationInView:self.answerPicker];
    if(coord.y <= 126 && coord.y >= 90) {
        //do something
    }
}
like image 25
Splash Avatar answered Apr 09 '23 02:04

Splash