#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textField;
// 日期选择控件
@property (nonatomic, strong) UIDatePicker *datePicker;
// 工具条
@property (nonatomic, strong) UIToolbar *toolbar;
@property (weak, nonatomic) IBOutlet UIView *v;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// inputView : 默认显示的是键盘
self.textField.inputView = self.datePicker;
// self.textField.inputAccessoryView = [UIButton buttonWithType:UIButtonTypeContactAdd];
self.textField.inputAccessoryView = self.toolbar;
}
// 点击取消
- (void)cancelClick {
// [self.textField resignFirstResponder];
[self.view endEditing:YES];
}
// 点击按钮
- (void)btnClick {
// 获取datepicker的日期
NSDate *date = self.datePicker.date;
// 将日期转为字符串
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy年MM月dd日"; // "HH:mm:ss"
NSString *dateStr = [formatter stringFromDate:date];
// [formatter dateFromString:];
// 把日期显示到文本框
self.textField.text = dateStr;
// 隐藏键盘
[self.textField resignFirstResponder];
}
#pragma mark - 懒加载
- (UIDatePicker *)datePicker {
if (_datePicker == nil) {
_datePicker = [[UIDatePicker alloc] init];
// 本地化
_datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"fr"];
// 显示模式 只显示日期
_datePicker.datePickerMode = UIDatePickerModeDate;
}
return _datePicker;
}
- (UIToolbar *)toolbar {
if (_toolbar == nil) {
_toolbar = [[UIToolbar alloc] init];
_toolbar.frame = CGRectMake(0, 0, 0, 44);
// 按钮 取消 弹簧 完成
// 取消 常用的创建方式
UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick)];
// 弹簧 系统类型
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
// 完成 自定义的view
UIButton *btn = [UIButton buttonWithType:UIButtonTypeContactAdd];
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithCustomView:btn];
_toolbar.items = @[cancel, flexSpace, done];
}
return _toolbar;
}
@end