UIDatePicker with “done” button

2019-03-25 19:06发布

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];
}

5条回答
▲ chillily
2楼-- · 2019-03-25 19:50

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

/*****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

- (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

查看更多
放我归山
3楼-- · 2019-03-25 19:51

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 UIBarButton Item 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.

查看更多
贪生不怕死
4楼-- · 2019-03-25 19:55

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)
}
查看更多
成全新的幸福
5楼-- · 2019-03-25 20:04

create a UIView and add it to the main view. Add a UIDatePicker to the new UIView. Add two UIButtons to the UIView.

查看更多
The star\"
6楼-- · 2019-03-25 20:06

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]);

}

查看更多
登录 后发表回答