iPhone display date picker on UITextField touch

后端 未结 8 1457
一生所求
一生所求 2020-11-30 00:08

I followed this thread: datepicker by clicking on textfield

I imported both of the following protocols:

@interface ViewController : UIViewController&         


        
8条回答
  •  再見小時候
    2020-11-30 00:43

    You could use the UITextField input view property. Just alloc init a regular UIDatePicker in code and assign it to the textfield's inputView. Doing this, the UIPickerView will be presented instead of the keyboard. If you need any code feel free to ask :)

    EDIT: code

    You fist hook up your textField with IB

    @interface myViewController 
    @property (nonatomic,weak) IBOutlet UITextField *myTextField;
    @end 
    

    In the implementation

    UIDatePicker *datePicker = [[UIDatePicker alloc]init];
    [datePicker setDate:[NSDate date]];
    [datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];       
    [self.myTextField setInputView:datePicker];
    

    That will bring up a UIDatePicker when you tap on the textField. Note the action that I added to the datePicker.

    [datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
    

    To update the textField each time that the user scrolls in the picker, you just need to implement the updateTextField method somewhere in the viewController

    -(void)updateTextField:(id)sender
    {
      UIDatePicker *picker = (UIDatePicker*)self.myTextField.inputView;
      self.myTextField.text = [NSString stringWithFormat:@"%@",picker.date];
    }
    

    With this last method, every time the user rotates the picker, the textfield will update!

    • You could use a NSDateFormatter to improve the output of the string.

提交回复
热议问题