How to dismiss a UIPicker that is connected to a U

2019-08-10 07:49发布

问题:

I have a UITextField, and when pushed a UIPickerView comes up to choose a value. How do I get the UIPickerView to dismiss once a value is chosen. Someone in another thread told me to resignFirstResponder the textfield, but my code isn't working. Any ideas? NOTE: I have two text fields and UI Pickers, that's why I have the 'if' 'else' statement.

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.ageTextField)
    {
        [ageTextField resignFirstResponder];
        [agePickerView removeFromSuperview];
        return YES;
    }
    else
    {
        [relationshipTextField resignFirstResponder];
        [relationshipPickerView removeFromSuperview];
        return YES;
    }
}

回答1:

Try the following code which may solve your problem.

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
 {
     if (textField == self.ageTextField) 
     {
         [ageTextField resignFirstResponder];
     } 
     else 
     {
         [relationshipTextField resignFirstResponder];
     }
     [pickerView removeFromSuperview];
     return YES; 
 }

or resign your keyboard on following method of UIPickerView.

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component


回答2:

Please try resigning the UITextField in UIPickerViewDelegate method as follows.

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    [self.ageTextField resignFirstResponder];
    pickerView.hidden = YES; //Show the pickerview again when you neeed it
}


回答3:

Implement the UIPickerViewDelegate protocol and implement the following method:

- (void) pickerView: (UIPickerView*) pickerView
       didSelectRow: (NSInteger)     row
        inComponent: (NSInteger)     component
{
  [self.ageTextField resignFirstResponder];
}