I am using an alarm functionality in my iphone app. Here when I put the state of uiswitch to "ON" and select a particular time from DatePicker, till user change the state of uiswitch to off, datepicker should show the selected time, and when the state is changed to off, date picker should show the current time, not previously selected one. I cannot find any option to set datepickers time value to current time programmatically.
setDate:
method is used for setting specific date
[yourDatePicker setDate:[NSDate date]];
It will set picker date and time to current date and time.
Try this,
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]];
}
}
In Swift:
yourDatePicker.setDate(date: NSDate, animated: Bool)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With