iOS UIDatePicker的使用(一)

#import "ViewController.h"


@interface ViewController ()


【iOS UIDatePicker的使用(一)】@property (weak, nonatomic) IBOutletUITextField *textField;


// 日期选择控件
@property (nonatomic,strong)UIDatePicker *datePicker;


// 工具条
@property (nonatomic,strong)UIToolbar *toolbar;


@property (weak, nonatomic) IBOutletUIView *v;


@end


@implementation ViewController


- (void)viewDidLoad {
[superviewDidLoad];

// inputView : 默认显示的是键盘
self.textField.inputView =self.datePicker;
//self.textField.inputAccessoryView = [UIButton buttonWithType:UIButtonTypeContactAdd];
self.textField.inputAccessoryView =self.toolbar;

}


// 点击取消
- (void)cancelClick {

//[self.textField resignFirstResponder];
[self.viewendEditing:YES];
}


// 点击按钮
- (void)btnClick {


// 获取datepicker的日期
NSDate *date = self.datePicker.date;

// 将日期转为字符串
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
formatter.dateFormat = @"yyyy年MM月dd日"; // "HH:mm:ss"
NSString *dateStr = [formatter stringFromDate:date];
//[formatter dateFromString:];

// 把日期显示到文本框
self.textField.text = dateStr;

// 隐藏键盘
[self.textFieldresignFirstResponder];

}




#pragma mark - 懒加载
- (UIDatePicker *)datePicker {

if (_datePicker ==nil) {

_datePicker = [[UIDatePickeralloc]init];

// 本地化
_datePicker.locale = [NSLocalelocaleWithLocaleIdentifier:@"fr"];

// 显示模式 只显示日期
_datePicker.datePickerMode =UIDatePickerModeDate;
}
return_datePicker;
}




- (UIToolbar *)toolbar {

if (_toolbar ==nil) {

_toolbar = [[UIToolbaralloc]init];
_toolbar.frame =CGRectMake(0,0,0, 44);

// 按钮取消 弹簧 完成
// 取消 常用的创建方式
UIBarButtonItem *cancel = [[UIBarButtonItemalloc]initWithTitle:@"取消"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(cancelClick)];

// 弹簧 系统类型
UIBarButtonItem *flexSpace = [[UIBarButtonItemalloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpacetarget:nilaction:nil];

// 完成 自定义的view
UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeContactAdd];
[btn addTarget:selfaction:@selector(btnClick)forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *done = [[UIBarButtonItemalloc]initWithCustomView:btn];

_toolbar.items =@[cancel, flexSpace, done];

}
return_toolbar;
}






@end

    推荐阅读