1 // 2 // ViewController.m 3 // 4.20 自定义生日键盘 4 // 5 // Created by hissia on 16/4/20. 6 // Copyright © 2016年 suiyue. All rights reserved. 7 // 8 9 #import "ViewController.h"10 11 @interface ViewController ()12 @property (weak, nonatomic) IBOutlet UITextField *birthdayLabel;13 14 @property (strong, nonatomic)UIDatePicker *datePicker;15 16 @end17 18 @implementation ViewController19 //是否允许输入文字20 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{21 return NO;22 }23 24 - (void)viewDidLoad {25 [super viewDidLoad];26 _birthdayLabel.delegate = self;27 28 // 设置自定义键盘29 [self setupBirthdayKeyboard]; 3031 }32 33 //自定义键盘格式34 - (void)setupBirthdayKeyboard35 {36 // 创建UIDatePicker,有默认的frame,所以不用设置尺寸37 UIDatePicker *picker = [[UIDatePicker alloc] init];38 39 // 赋值 _datePicker40 _datePicker = picker;41 42 // 设置本地化(本地语言)43 picker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];44 45 // 设置时间显示格式,还有其他好多种46 picker.datePickerMode = UIDatePickerModeDate;47 48 //监听UIDatePicker的滚动49 [picker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];50 self.birthdayLabel.inputView = picker;51 }52 53 - (void)dateChange:(UIDatePicker *)datePicker54 {55 // 这样就可以获得生日键盘的 datePicker.date56 // NSLog(@"%@",datePicker.date);57 // NSLog(@"%s",__func__); 此打印方法的的各种属性58 59 //把获得的日期转化成字符串,赋值到birthdayLabel中60 NSDateFormatter *fmt = [[NSDateFormatter alloc] init];61 fmt.dateFormat = @"yyyy-MM-dd";62 NSString *datestr = [fmt stringFromDate:datePicker.date];63 _birthdayLabel.text = datestr;64 65 }66 67 //文本框开始编辑时候监听事件68 - (void)textFieldDidBeginEditing:(UITextField *)textField69 {70 //获取当前dataPicker的日期71 [self dateChange:_datePicker];72 }73 //点击空白处弹回生日键盘74 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event75 {76 [self.view endEditing:YES];77 }78 @end