How to Show UIPickerView when selecting UITextField

前端 未结 8 535
Happy的楠姐
Happy的楠姐 2020-12-08 03:52

Here is a screenshot of what I did till now:

\"enter

So what I am trying to do

8条回答
  •  一整个雨季
    2020-12-08 04:14

    Since iOS 3.2, UITextField supports the inputView property to assign a custom view to be used as a keyboard, which provides a way to display a UIPickerView:

    You could use the inputView property of the UITextField, probably combined with the inputAccessoryView property. You assign your pickerView to the inputView property, and, to dismiss the picker, a done button to the inputAccessoryView property.

    UIPickerView *myPickerView = [[UIPickerView alloc] init];
    //myPickerView configuration here...
    myTextField.inputView = myPickerView;
    

    Like that. This will not give you a direct way to dismiss the view since your UIPickerView has no return button, which is why I recommend to use the inputAccessoryView property to display a toolbar with a done button (the bar is just for aesthetics, you might as well just use a UIButton object):

    UIToolbar *myToolbar = [[UIToolbar alloc] initWithFrame:
     CGRectMake(0,0, 320, 44)]; //should code with variables to support view resizing
    UIBarButtonItem *doneButton =
     [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
     target:self action:@selector(inputAccessoryViewDidFinish)];
     //using default text field delegate method here, here you could call
     //myTextField.resignFirstResponder to dismiss the views
    [myToolbar setItems:[NSArray arrayWithObject: doneButton] animated:NO];
    myTextField.inputAccessoryView = myToolbar;
    

提交回复
热议问题