How to display UIDatePicker if user hit the UIText

2020-05-26 17:26发布

问题:

I'd like to Display UIDatePicker only when user the UITextField is Clicked. When the date is picked, it should be shown in the same UITextField.I want to implement UIDatePicker programmatically.I know how to write the code of UITextField Programmatically. I even don't know how to call the UIDatePicker.

Date of Birth.m

UITextField txtDOB=[[UITextField alloc]initWithFrame:CGRectMake(10, 190, 300, 20)];

txtDOB.borderStyle=UITextBorderStyleNone;

txtDOB.backgroundColor=[UIColor clearColor];

[txtDOB setUserInteractionEnabled:NO];

txtDOB.font=[UIFont systemFontOfSize:14.0];

txtDOB.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;

txtDOB.textAlignment=NSTextAlignmentLeft;

txtDOB.delegate=self;

[self.view addSubview:txtDOB];

回答1:

The easiest way is to implement the datePicker is as following:

Create the datePicker:

self.datePicker = [[UIDatePicker alloc] initWithFrame:CGRectZero];
[self.datePicker setDatePickerMode:UIDatePickerModeDate];
[self.datePicker addTarget:self action:@selector(onDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];

Then link the datePicker to the textfield inputView:

self.textField.inputView = self.pickerView;

In the end you can catch the action when a date was picked, and convert the date to a string, to show the selected date in the textField

- (void)onDatePickerValueChanged:(UIDatePicker *)datePicker
{
    self.textField.text = [self.dateFormatter stringFromDate:datePicker.date];
}


回答2:

    UIDatePicker *picker1   = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 210, 320, 216)];
    [picker1 setDatePickerMode:UIDatePickerModeDate];
    picker1.backgroundColor = [UIColor whiteColor];
    [picker1 addTarget:self action:@selector(startDateSelected:) forControlEvents:UIControlEventValueChanged];

//    [picker1 addSubview:toolBar];
    self.birthTxt.inputView  = picker1; // Here birthTxt is Textfield Name replace with your name


回答3:

Before going to this code, you need to just know about UIActionSheet and You need to implement UIActionShetDelegate and UITextFieldDelegate In the textFieldDidBeginEditing you need to show the action sheet as below:

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
   UIActionSheet *asheet = [[UIActionSheet alloc] initWithTitle:@"Select Date" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Select", nil];
  [asheet showInView:[self.view superview]];
  [asheet setFrame:CGRectMake(0, 117, 320, 383)];
}

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
  {
    UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 320, 240)];

   [pickerView setMinuteInterval:5];
   [pickerView setTag: DatePickerTag];

  [actionSheet addSubview:pickerView];
  NSArray *subviews = [actionSheet subviews];

  [[subviews objectAtIndex:SelectButtonIndex] setFrame:CGRectMake(20, 250, 280, 46)];
  [[subviews objectAtIndex:CancelButtonIndex] setFrame:CGRectMake(20, 300, 280, 46)];

}


回答4:

  • First indicate that your class conforms to the UITextFieldDelegate protocol

  • Then in viewDidLoad set the delegate and tag of your text field.

     yourTextField.delegate = self;  
     yourTextField.tag = 111;
    
  • Then implement the following delegate method:

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {   
        if (textField.tag==111) {  
            [self showDatePicker];  
        }  
        return YES;  
    }
    
  • Now implement a function showDatePicker

    - (void)showDatePicker {  
        datePicker = [[UIDatePicker alloc] init];
        datePicker.backgroundColor=[UIColor whiteColor];
    
        UIToolbar *toolbar = [[UIToolbar alloc]init];
        [toolbar sizeToFit];
    
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(showSelectedDate)];    
    
        doneBtn.tintColor = [UIColor whiteColor];  
    
        UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];    
    
        toolbar.backgroundColor = [UIColor colorWithRed:5.0/255.0 green:110.0/255.0 blue:170.0/255.0 alpha:1];  
    
        [toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft,doneBtn ,nil]];  
    
        [yourTextField setInputAccessoryView:toolBar];  
    
        yourTextField.inputView = datePicker;   
    }
    

OR you can do it simply in your viewDidLoad as follows:

datePicker = [[UIDatePicker alloc] init];
datePicker.backgroundColor = [UIColor whiteColor];  

UIToolbar *toolbar = [[UIToolbar alloc]init]; 

[toolbar sizeToFit];    

 UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self
 action:@selector(showSelectedDate)];    

 doneBtn.tintColor = [UIColor whiteColor];  

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

toolbar.backgroundColor = [UIColor colorWithRed:5.0/255.0 green:110.0/255.0 blue:170.0/255.0 alpha:1];  

[toolBar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft, doneBtn , nil]];  

[yourTextField setInputAccessoryView:toolbar];  

yourTextField.inputView = datePicker;


回答5:

You need to add a proper selector when editing begins on UITexfield, use below code

 [txtDOB addTarget:self action:@selector(textbeginEditing:) forControlEvents:UIControlEventEditingDidBegin];

And then implelemt the textbeginEditing method to open the datepicker.

-(void)textbeginEditing:(id)sender{

UIActionSheet __autoreleasing * date_sheet = [[UIActionSheet alloc] initWithTitle:@"Select the date" delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];

date_sheet.tag = 2;

[date_sheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];

CGRect pickerFrame = CGRectMake(0, 40, 0, 0);

UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];

datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.hidden = NO;
datePicker.date = [NSDate date];

// Implement the method labelChange
 [datePicker addTarget:self
                action:@selector(labelChange:)
      forControlEvents:UIControlEventValueChanged];


[date_sheet addSubview:datePicker];

UISegmentedControl __autoreleasing *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];

closeButton.momentary = YES;    
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);    
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;    
closeButton.tintColor = [UIColor blackColor];

[closeButton addTarget:self action:@selector(dissmissDatePicker:) forControlEvents:UIControlEventValueChanged];

[date_sheet addSubview:closeButton];
[date_sheet showInView:[[UIApplication sharedApplication] keyWindow]];    
[date_sheet setBounds:CGRectMake(0, 0, 320, 400)];
}

labelChange method implementation

-(void)labelChange:(UIDatePicker *)sender{
NSDateFormatter __autoreleasing *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
 dateFormat.dateStyle = NSDateFormatterMediumStyle;
 NSString *dateString =  [dateFormat stringFromDate:sender.date];
 txtDOB.text = dateString; 
}


回答6:

This will be simple, try this
When U click the textField, this method is called.

-(void)textFieldDidBeginEditing:(UITextField *)textField
{  

Then, we dont want to display the keyboard.

[textField resignFirstResponder];  

Then, to display the datePicker

datePicker=[[UIDatePicker alloc]init];
[datePicker setFrame:CGRectMake(<ur dimension>)];
datePicker.datePickerMode=UIDatePickerModeDateAndTime;
datePicker.timeZone = [NSTimeZone localTimeZone];
[datePicker addTarget:self action:@selector(done) forControlEvents:UIControlEventValueChanged];  

This will display the datePicker.
Then U want to display the selected value in textField

-(void)done
{
  NSString *dateStri=[dateFormater stringFromDate:datePicker.date];
    [timingTextField setText:[NSString stringWithFormat:@"%@",dateStri]];
}  

Try this, and update me the result



回答7:

First make userIntraction enable

[txtDOB setUserInteractionEnabled:YES];

and add your picker view as input view of this text filed

[txtDOB setInputView:pickerview]