【问题标题】:programmatically setting DatePicker time to current time以编程方式将 DatePicker 时间设置为当前时间
【发布时间】:2013-06-27 04:05:51
【问题描述】:

我在我的 iPhone 应用程序中使用了闹钟功能。在这里,当我将 uiswitch 的状态设置为“ON”并从 DatePicker 中选择特定时间时,直到用户将 uiswitch 的状态更改为 off,datepicker 应显示所选时间,当状态更改为 off 时,日期选择器应显示当前时间,之前没有选择一个。我找不到以编程方式将日期选择器时间值设置为当前时间的任何选项。

【问题讨论】:

  • 查看 UIDatePickerdate 属性的文档。

标签: ios uidatepicker


【解决方案1】:

setDate:方法用于设置具体日期

[yourDatePicker setDate:[NSDate date]];

它将选择器日期和时间设置为当前日期和时间。

【讨论】:

    【解决方案2】:

    试试这个,

    ViewController.h

    @interface ViewController : UIViewController
    {
      IBOutlet UISwitch *onOffSwitch;
      UIDatePicker *myPicker;
    }
    -(IBAction)onOffSwitch:(id)sender;
    
    @end
    

    ViewController.m

      - (void)viewDidLoad
        {
        [super viewDidLoad];
        CGRect pickerFrame = CGRectMake(0,250,0,0);
        myPicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
        [self.view addSubview:myPicker];
        [myPicker release];
        }
    
        -(IBAction)onOffSwitch:(id)sender{
    
        if(onOffSwitch.on) {
    
            NSString *dateStr = @"Tue, 25 May 2010 12:53:58 +0000";
            // Convert string to date object
            NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
            [dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"];
            NSDate *date = [dateFormat dateFromString:dateStr];
            [myPicker setDate:date];
        }
        else 
        {
            [myPicker setDate:[NSDate date]];
        }
    }
    

    【讨论】:

      【解决方案3】:

      在斯威夫特中:

      yourDatePicker.setDate(date: NSDate, animated: Bool)
      

      【讨论】:

      • Swift 4.0: yourDatePicker.setDate(Date(), 动画: true)
      猜你喜欢
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 2013-07-30
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      相关资源
      最近更新 更多