简体   繁体   English

单击UIBarButtonItem时显示UIDatePicker及其工具栏

[英]Show UIDatePicker and its toolbar when clicking on a UIBarButtonItem

In my app's ViewController, I have 3 differents items: 在我的应用的ViewController中,我有3个不同的项目:

@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. 当我单击dataSelect UIBarButtonItem时,我需要能够显示datePicker和dateToolbar。

In a previous project, I displayed the dataPicker and it's toolbar (with "ok" and "cancel" buttons) using the inputView of a UITextField 在上一个项目中,我使用UITextField的inputView显示了dataPicker及其工具栏(带有“确定”和“取消”按钮)

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 ? 由于UIBarButtonItem没有任何inputView属性,是否有类似的方法呢?

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 我认为您应该设置UIBarButtonItem的目标操作来创建选择器

-(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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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