(Swift)
import UIKit class ViewController: UIViewController { var datePicker: UIDatePicker! func datePickerDateChanged(datePicker: UIDatePicker) { println("Selected date = \(datePicker.date)") } override func viewDidLoad() { super.viewDidLoad() datePicker = UIDatePicker() datePicker.center = view.center view.addSubview(datePicker) datePicker.addTarget(self, action: "datePickerDateChanged:", forControlEvents: .ValueChanged) /* set the minimum and the maximum dates that it can display */ let oneYearTime:NSTimeInterval = 365 * 24 * 60 * 60 let todayDate = NSDate() let oneYearFromToday = todayDate.dateByAddingTimeInterval(oneYearTime) let twoYearsFromToday = todayDate.dateByAddingTimeInterval(2 * oneYearTime) datePicker.minimumDate = oneYearFromToday datePicker.maximumDate = twoYearsFromToday } }
(Objective-C)
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIDatePicker *myDatePicker; @end @implementation ViewController - (void) datePickerDateChanged:(UIDatePicker *)paramDatePicker { if ([paramDatePicker isEqual:self.myDatePicker]) { NSLog(@"Selected date = %@", paramDatePicker.date); } } - (void)viewDidLoad { [super viewDidLoad]; self.myDatePicker = [[UIDatePicker alloc] init]; self.myDatePicker.center = self.view.center; [self.view addSubview:self.myDatePicker]; [self.myDatePicker addTarget:self action:@selector(datePickerDateChanged:) forControlEvents:UIControlEventValueChanged]; NSTimeInterval oneYearTime = 365 * 24 * 60 * 60; NSDate *todayDate = [NSDate date]; NSDate *oneYearFromToday = [todayDate dateByAddingTimeInterval:oneYearTime]; NSDate *twoYearsFromToday = [todayDate dateByAddingTimeInterval:2 * oneYearTime]; self.myDatePicker.minimumDate = oneYearFromToday; self.myDatePicker.maximumDate = twoYearsFromToday; } @end
时间: 2024-10-28 08:30:57