iOS开发技巧 - 使用UIDatePicker来选择日期和时间

(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 = * * *
let todayDate = NSDate()
let oneYearFromToday = todayDate.dateByAddingTimeInterval(oneYearTime)
let twoYearsFromToday = todayDate.dateByAddingTimeInterval( * 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 = * * * ;
NSDate *todayDate = [NSDate date];
NSDate *oneYearFromToday = [todayDate dateByAddingTimeInterval:oneYearTime];
NSDate *twoYearsFromToday = [todayDate dateByAddingTimeInterval: * oneYearTime];
self.myDatePicker.minimumDate = oneYearFromToday;
self.myDatePicker.maximumDate = twoYearsFromToday;
} @end
上一篇:Android控件开发——ListView


下一篇:【bzoj4636】蒟蒻的数列 离散化+线段树