思路:
1. 创建datepicker 对象
self.datePicker = [[UIDatePicker alloc] init];
//设置语言格式
self.datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh"];
//日期格式
self.datePicker.datePickerMode = UIDatePickerModeDate;
2. textfeild的属性inputView更改为datepicker对象
//设置textField的键盘
self.dateTextFeild.inputView = self.datePicker;
3. 重写toolbar,为toolbar上添加三个item,再将toolbar对象添加到textfeild的另外一个属性inputAccessoryView
//代码创建toolbar
- (void)createToolbar {
//代码创建 UIToolbar
UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.backgroundColor = [UIColor grayColor];
//屏幕宽度
CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
toolbar.frame = CGRectMake(0, 0, screenW, 40);
//设置toolbar上的item (上一个)
UIBarButtonItem *lastItem = [[UIBarButtonItem alloc] initWithTitle:@"上一个" style:UIBarButtonItemStylePlain target:nil action:nil];
//设置上一个和下一个的item之间的固定间距
UIBarButtonItem *fixedSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
fixedSpaceItem.width = 20;
//设置item(下一个)
UIBarButtonItem *nextItem = [[UIBarButtonItem alloc] initWithTitle:@"下一个" style:UIBarButtonItemStylePlain target:nil action:nil];
//设置下一个跟Done item之间的间距 UIBarButtonSystemItemFlexibleSpace 此枚举为弹簧效果
UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
//设置item(Done)
UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:nil action:nil];
//toolbar属性设置
#warning 注意数组的顺序
toolbar.items = @[lastItem, fixedSpaceItem, nextItem, flexibleItem, doneItem];
self.dateTextFeild.inputAccessoryView = toolbar;
}