开发者

I want to change UIDatePicker's datePickerMode dynamically

I want to be able to the one date picker can input month-day-year-hour-minute. I know if two UIDatePicker objects were it's possible. e.g. UIDatePicker obj1; //for month-day-year UIDatePicker obj2; //for hour-minute

But I don't want to have two UIDatePicker for one date input:month-day-year-hour-minute. So I made one UIDatePicker and one UIButton. The button is for change UIDatePicker's datePickerMode.

The picker's figure can be changed. [mm|dd|yyyy] <--> [hh:mm]

But when the picker's mode changes as following,

[hh:mm] -> [mm|dd|yyyy] -> [hh:mm]

the hour-date of the picker becomes 0开发者_StackOverflow中文版0:00, even if set like 11:59 before the mode changed.

Why?

The month-day-year never changes however the mode is changed.


the hour-date of the picker becomes 00:00, even if set like 11:59 before the mode changed. Why?

Probably because the date picker stores dates with the time set to midnight if it's in mm|dd|yyyy mode. So you would have to store the selected time in a separate NSDate object, and when the user switches from mm|dd|yyyy to hh:mm, set the date picker's date to the correct date and time (by extracting time and minute from the one date and year/month/day from the other via NSDateComponents and compositing a new date with all the components).


Thank you for your answer.

I added 3 lines in my original codes as following.
It seems to be good so far.

    - (IBAction) switchDateTime {
  switch (datePicker_.datePickerMode) {
    case UIDatePickerModeDate: {
      datePicker_.datePickerMode = UIDatePickerModeDateAndTime;
      [swBtn_ setTitle:NSLocalizedString(@"swichBtn_date", @"") forState:UIControlStateNormal];
    } break;
    case UIDatePickerModeDateAndTime: {
      NSDate *tmp = [datePicker_.date copy];//<- added
      datePicker_.datePickerMode = UIDatePickerModeDate;
      datePicker_.date = tmp;               //<- added
      [tmp release];
      [swBtn_ setTitle:NSLocalizedString(@"swichBtn_time", @"") forState:UIControlStateNormal];
    } break;
    default:
      assert(0);
      break;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜