简体   繁体   中英

Show UIDatePicker and its toolbar when clicking on a UIBarButtonItem

In my app's ViewController, I have 3 differents items:

@property (weak, nonatomic) IBOutlet UIBarButtonItem *dateSelect;
@property (weak, nonatomic) IBOutlet UIToolbar *dateToolbar;
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;

Those 3 items are also defined in my storyboard file.

I need to be able to show the datePicker and the dateToolbar when I click on the dataSelect UIBarButtonItem.

In a previous project, I displayed the dataPicker and it's toolbar (with "ok" and "cancel" buttons) using the inputView of a UITextField

self.date.inputView = self.datePicker;
self.date.inputAccessoryView = self.dateToolbar;

As UIBarButtonItem does not have any inputView property, is there a similar way to do so ?

The approach I suggest is defining a view controller with picker and toolbar and present it in popover and hence in the button press action itself you can show/add values by showing this popover

Delegates will be needed for dismissal and passing the values in this approch.And it is a reusable way

I think you should set the target action of the UIBarButtonItem to create the picker

-(void) createPicker {
    datePicker = [[UIPickerView alloc] init];
    datePicker.frame = CGRectMake(0, 200, 320, 240);
    datePicker.delegate = self;
    datePicker.dataSource = self;
    datePicker.showsSelectionIndicator = YES;

    [self.view addSubview:datePicker];
    if(!_isToolBarShow) {
    _isToolBarShow = YES;
    toolDismiss.frame = CGRectMake(0, 160, 320, 40);
    }
}

And to remove you can give target action to your OK/Cancel button

- (IBAction) dismissKeyBoardBtnAction:(id)sender {

    if (datePicker != nil) {
        [datePicker removeFromSuperview];
        [datePicker release];
        datePicker = nil;
                _isToolBarShow = NO;
        toolDismiss.frame = CGRectMake(0, 480, toolDismiss.frame.size.width, toolDismiss.frame.size.height);
    }
}

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