简体   繁体   中英

How to set UIPickerView as inputView to UITextField in iPhone

I am trying to open UIPickerView as inputView to UITextfield .

Here is my code in textFieldDidBeginEditing :

  UIPickerView *categoryPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 43, 320, 480)];
    categoryPicker.delegate = self;
    categoryPicker.dataSource = self;
    [categoryPicker  setShowsSelectionIndicator:YES];
    txtCategory.inputView =  categoryPicker;

  UIToolbar *_providerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
    _providerToolbar.barStyle = UIBarStyleBlackOpaque;
    [_providerToolbar sizeToFit];

    NSMutableArray *barItems = [[NSMutableArray alloc] init];
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItems addObject:flexSpace];

    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissActionSheet)];

    [barItems addObject:doneBtn];

    [_providerToolbar setItems:barItems animated:YES];
    txtCategory.inputAccessoryView = _providerToolbar;

It's working fine for first time, but when I am selecting any value from UIPickerView it's hiding and my UITextfield is editable and UIPickerView is not showing at that time. What am I doing wrong?

I'd suggest you to move your code to viewDidLoad: . Because textFieldDidBeginEditing: is called when textField loads the keyboard for it. So It is not the right time to change the inputAccessoryView of the textField.

Use this...

    NSDate *now = [NSDate date];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

    [dateFormat setDateFormat:@"dd MMM, yyyy"];

    UIDatePicker *datePicker = [[UIDatePicker alloc] init];

    [datePicker setMaximumDate:now];

    datePicker.datePickerMode = UIDatePickerModeDate;

    txtForDate.text = [dateFormat stringFromDate:datePicker.date];

    [datePicker addTarget:self action:@selector(updateTextField:)
         forControlEvents:UIControlEventValueChanged];

    [txtForDate setInputView:datePicker];

// txtForDate is UITextField

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM