ios 带有“完成”按钮的 UIDatePicker

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27050988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:44:27  来源:igfitidea点击:

UIDatePicker with "done" button

iosbuttondatepicker

提问by Marcos Dávalos

I need to add a "done" button to my date picker like in this image:

我需要在我的日期选择器中添加一个“完成”按钮,如下图所示:

enter image description here

在此处输入图片说明

This is my code:

这是我的代码:

-(IBAction)chooseDate:(id)sender{
self.datepicker= [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];
    self.datepicker.datePickerMode = UIDatePickerModeDate;
    datepicker.backgroundColor = Rgb2UIColor(52, 170, 220);

    [self.btnDone
                addTarget:self
                action:@selector(SetDatePickerTime:)
                forControlEvents:UIControlEventTouchDown];

 [self.view addSubview:self.datepicker];
}

采纳答案by Coach

Create a date picker, then add it as the input view of the field in question (self.fieldInQuestion.inputView = datePicker). Next, create a UIToolBar(height 44) with UIBarButtonItem on it with the title "Done", target of self, and a selector (ex. @selector(done)). Add this as the input accessory view of the same field you made the date picker an input view for (self.fieldInQuestion.inputAccessoryView = UIToolbarInstance). In the selector method (-(void)done in the example above), make sure you use [self.fieldInQuestion resignFirstResponder] and it will dismiss it.

创建一个日期选择器,然后将其添加为相关字段的输入视图 ( self.fieldInQuestion.inputView = datePicker)。接下来,创建一个UIToolBar(高度 44),UIBarButton上面有标题“完成”的 Item,目标是 self 和一个选择器(例如 @selector(done))。将此添加为您将日期选择器设为 ( ) 的输入视图的同一字段的输入附件视图self.fieldInQuestion.inputAccessoryView = UIToolbarInstance。在选择器方法中(-(void)done 在上面的例子中),确保你使用 [self.fieldInQuestion resignFirstResponder] 并且它会关闭它。

回答by lifeisfoo

With Swift

与斯威夫特

// Place this code inside your ViewController or where you want ;)

var txtField: UITextField = UITextField(frame: CGRectMake(0, 0, 200, 50))

// the formatter should be "compliant" to the UIDatePickerMode selected below
var dateFormatter: NSDateFormatter {
    let formatter = NSDateFormatter()
    // customize the locale for the formatter if you want
    //formatter.locale = NSLocale(localeIdentifier: "it_IT")
    formatter.dateFormat = "dd/MM/yyyy"
    return formatter
}

override func viewDidLoad() {
    super.viewDidLoad()

    // date picker setup
    let datePickerView:UIDatePicker = UIDatePicker()

    // choose the mode you want
    // other options are: DateAndTime, Time, CountDownTimer
    datePickerView.datePickerMode = UIDatePickerMode.Date

    // choose your locale or leave the default (system)
    //datePickerView.locale = NSLocale.init(localeIdentifier: "it_IT")

    datePickerView.addTarget(self, action: "onDatePickerValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
    txtField.inputView = datePickerView

    // datepicker toolbar setup
    let toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.Default
    toolBar.translucent = true
    let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "doneDatePickerPressed")

    // if you remove the space element, the "done" button will be left aligned
    // you can add more items if you want
    toolBar.setItems([space, doneButton], animated: false)
    toolBar.userInteractionEnabled = true
    toolBar.sizeToFit()

    txtField.inputAccessoryView = toolBar

    self.view.addSubview(txtField)
}

func doneDatePickerPressed(){
    self.view.endEditing(true)
}

func onDatePickerValueChanged(datePicker: UIDatePicker) {
    self.txtField = dateFormatter.stringFromDate(datePicker.date)
}

回答by iSankha007

The reference image of your question is showing that the app is using UIToolbar and i will assume that when tapping on date text field the datepicker with done button appears.And for this in some.h file

您问题的参考图像显示该应用程序正在使用 UIToolbar,我将假设当点击日期文本字段时,会出现带有完成按钮的日期选择器。为此,在 some.h 文件中

/*****keyboard Done button   ***/



#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
   IBOutlet UIDatePicker *picker1;
    IBOutlet UITextField *txtFld;

}
@property (nonatomic, retain) UIToolbar *keyboardToolbar;

@end

in some.m file

在一些.m文件中

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
 picker1=[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];//frames are just for demo
 [txtFld setInputView:picker1];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    if(keyboardToolbar == nil) {
        keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 410, 320, 44)] ;
        [keyboardToolbar setBarStyle:UIBarStyleBlackTranslucent];
        [keyboardToolbar sizeToFit];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.4];

        UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

        UIBarButtonItem *doneButton1 =[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyboard)];
        NSArray *itemsArray = [NSArray arrayWithObjects:flexButton,doneButton1, nil];

        [keyboardToolbar setItems:itemsArray];


        [txtFld setInputAccessoryView:keyboardToolbar];
        [self.view addSubview:keyboardToolbar];
        [UIView commitAnimations];
    }
}



-(void)resignKeyboard {

    [keyboardToolbar removeFromSuperview];
    [txtFld resignFirstResponder];
///do nescessary date calculation here

    }

enter image description here

在此处输入图片说明

回答by iOS

In Swift 5

在斯威夫特 5

//Create this variable
var picker:UIDatePicker?

//Write Date picker code
picker = UIDatePicker()
dobTF.inputView = picker//Change your textfield name
picker?.addTarget(self, action: #selector(handleDatePicker), for: .valueChanged)
picker?.datePickerMode = .date

//Write toolbar code for done button
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(onClickDoneButton))
toolBar.setItems([space, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
toolBar.sizeToFit()
dobTF.inputAccessoryView = toolBar

//Date picker function
@objc func handleDatePicker() {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy" //Change your date formate
    let strDate = dateFormatter.string(from: picker!.date)
    dobTF.text = strDate
}

//Toolbar done button function
@objc func onClickDoneButton() {
    self.view.endEditing(true)
}

回答by Marcos Dávalos

I DO!!!!

我愿意!!!!

-(IBAction)ChooseDate:(id)sender{

btnDone = [UIButton buttonWithType:UIButtonTypeRoundedRect];

[done setTitle:@"GO!" forState:UIControlStateNormal];
btnDone.backgroundColor = UIColorFromRGB(0x1F1F21);
btnDone.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[btnDone addTarget:self
           action:@selector(HidePicker:)
 forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnDone];


    self.datepicker= [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];
    self.datepicker.datePickerMode = UIDatePickerModeDate;
    datepicker.backgroundColor = Rgb2UIColor(52, 170, 220);

    [self.view addSubview:self.datepicker];
}


-(IBAction)HidePicker:(id)sender{
[UIView animateWithDuration:0.5
                 animations:^{
                     datepicker.frame = CGRectMake(0, -250, 320, 50);
                 } completion:^(BOOL finished) {
                     [datepicker removeFromSuperview];
                     [btnDone removeFromSuperview];
                 }];

[self.datepicker removeFromSuperview];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"ddMMyyyy"];

//NSLOG
NSLog(@"%@",[outputFormatter stringFromDate:self.datepicker.date]);

}

}