XCode: Displaying a UIDatePicker when user clicks on UITextbox

前端 未结 4 1443
一个人的身影
一个人的身影 2020-12-29 00:32

I have already researched this topic to death and found people posting the exact same question on a number of websites including right here in stackoverflow.

I have

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 00:59

    I had the same issue using Storyboard. Here is how I resolved it:

    Overview: I alloc and initialize my UIDatePicker property in viewDidLoad:. I then set the inputView property of my textfield to my datepicker property.

    Here is my code: In TripViewController.h:

    @property (nonatomic,strong) IBOutlet UIDatePicker *datePicker;
    

    In TripViewController.m:

    @synthesize datePicker;
    ...
    -(void)viewDidLoad {
    ...
    self.datePicker = [[UIDatePicker alloc]init];
    [self.datePicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
    self.dateField.inputView = self.datePicker;
    }
    

    I then implement my method, dateChanged so that whenever the date picker wheel stops moving, my textfield is updated.

    - (void)dateChanged
    {
    NSDate *date = self.datePicker.date;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateStyle:NSDateFormatterMediumStyle];
    self.dateField.text = [dateFormat stringFromDate:date];
    }
    

提交回复
热议问题