How to display UIDatePicker if user hit the UITextfield Programmatically

后端 未结 7 1323
刺人心
刺人心 2021-02-05 14:31

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

7条回答
  •  梦毁少年i
    2021-02-05 15:11

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

提交回复
热议问题