Search code examples
iosxcodereturnuipickerviewnumpad

How could I open a picker view upon hitting return key or tapping anywhere on the screen?


I'm trying to create an unit converter app and not sure which command to implement for proceeding further. Below code would return to main screen upon hitting return key in number pad or tapping anywhere on the screen.

- (IBAction)textFieldReturn:(id)sender
{
    [sender resignFirstResponder];    
    [self selectButton:nil];
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch* touch= [[event allTouches]anyObject];    
    if ([_distance isFirstResponder] && [touch view] != _distance)
    {
        [_distance resignFirstResponder];
    }

    [super touchesBegan:touches withEvent:event];
}

And This code would open a picker view:

- (IBAction)selectButton:(id)sender
{
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.3];
   pickerViewContainer.frame=CGRectMake(0, 200, 320, 261);
  [UIView commitAnimations];
   pickerViewContainer.hidden=NO;
}

How could I open a picker view upon hitting return key or tapping anywhere on the screen? Kindly assist.


Solution

  • You can add UITapGestureRecognizer on you main view like this. And can utilize UITextFieldDelegate to check for return button pressed.

    - (void) viewDidLoad {
        [super viewDidLoad];
        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openPickerView)];
        [self.view addGestureRecognizer:gestureRecognizer];
        [self.textField setDelegate:self];
    }
    
    //UITextFieldDelegate
    - (BOOL)textFieldShouldReturn:(UITextField *)textField{
        [self openPickerView];
        return YES;
    }
    
    
    - (void)openPickerView
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        pickerViewContainer.frame=CGRectMake(0, 200, 320, 261);
        [UIView commitAnimations];
        pickerViewContainer.hidden=NO;
    }