如何将UIPickerView设置为iPhone中的UITextField的inputView

时间:2015-08-28 04:59:34

标签: ios objective-c uitextfield uipickerview

我正在尝试将UIPickerView作为inputView打开到UITextfield

以下是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;

它第一次正常工作,但是当我从UIPickerView中选择隐藏的任何值时,我的UITextfield是可编辑的,当时UIPickerView没有显示。我做错了什么?

2 个答案:

答案 0 :(得分:0)

我建议您将代码移至viewDidLoad:。因为textField为其加载键盘时会调用textFieldDidBeginEditing:。所以现在不是更改textField的inputAccessoryView的正确时间。

答案 1 :(得分:0)

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是UITextField