弹出生日键盘

 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 () <UITextFieldDelegate>
12 @property (weak, nonatomic) IBOutlet UITextField *birthdayLabel;
13 
14 @property (strong, nonatomic)UIDatePicker *datePicker;
15 
16 @end
17 
18 @implementation ViewController
19 //是否允许输入文字
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];
30 31 } 32 33 //自定义键盘格式 34 - (void)setupBirthdayKeyboard 35 { 36 // 创建UIDatePicker,有默认的frame,所以不用设置尺寸 37 UIDatePicker *picker = [[UIDatePicker alloc] init]; 38 39 // 赋值 _datePicker 40 _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 *)datePicker 54 { 55 // 这样就可以获得生日键盘的 datePicker.date 56 // 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 *)textField 69 { 70 //获取当前dataPicker的日期 71 [self dateChange:_datePicker]; 72 } 73 //点击空白处弹回生日键盘 74 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 75 { 76 [self.view endEditing:YES]; 77 } 78 @end

 

posted @ 2016-04-21 08:03  hissia  阅读(452)  评论(0编辑  收藏  举报