//程序員
// ViewController.matom
// 手寫UIDatePickerspa
//.net
// Created by 非凡 程序員 on 15/11/13.3d
// Copyright (c) 2015年 非凡 程序員. All rights reserved.orm
//事件
.h文件字符串
#import <UIKit/UIKit.h>get
@interface ViewController : UIViewControllerstring
@property(nonatomic,strong)UIDatePicker *datePicker;
---------------------------------
.m文件
#import "ViewController.h"
@interface ViewController ()
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//定義一個datePicker
_datePicker = [ [ UIDatePicker alloc ] initWithFrame:CGRectMake (10, 10, 100, 100) ] ;
//設置datePicker的樣式
_datePicker.datePickerMode = UIDatePickerModeDateAndTime ;
//設置datePicker的時間差
_datePicker.minuteInterval = 6;
//設置datePicker的最小時間爲當前時間
_datePicker.minimumDate = [ NSDate date ] ;
//對datePicker添加事件
[ _datePicker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged ] ;
//將控件添加在頁面上
[ self.view addSubview:_datePicker ] ;
}
//當datePicker值發生改變會回調的自定義方法
- ( void ) dateChange : ( UIDatePicker * ) sender {
NSDate * date = _datePicker.date ; //獲取datePicker的時間
NSLog ( @" %@ " , date )
;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
--------------------------------------------------------------------------------------------------------------
// ViewController.m
// UIDatePicker
//
// Created by 非凡 程序員 on 15/11/13.
// Copyright (c) 2015年 非凡 程序員. All rights reserved.
//
.h文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
@end
-----------------------------------
.m文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// UIDatePicker 是一個控制器類,他是UIControl的子類,專門用於接受日期、時間和持續時長的輸入。日期選取器的各列會按照指定的風格進行自動配置
// UIDatePicker 依賴於 NSDate 類
_datePicker.minuteInterval=6;
//設置datePicker的樣式
_datePicker.datePickerMode=UIDatePickerModeDate;
// 格式化一個字符串型的時間爲NSDate類型
NSString *string=@"2012-12-22";
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date=[formatter dateFromString:string];
// 設置datePicker的最小時間
_datePicker.minimumDate=date;
//對datePicker添加事件
[_datePicker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];
}
//當datePicker值發生改變會回調的自定義方法
-(void)dateChange:(UIDatePicker *)sender{
NSDate *date=_datePicker.date;
NSLog(@"%@",date);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end