代码实现日期选择器UIDatePicker使用

来源:互联网 发布:圆点软件下载 编辑:程序博客网 时间:2024/05/06 08:02

实现了一个中文显示的日期选择器,然后初始化一个定位的年份信息,再将用户选择的信息显示在UITextField中,大提思路是这样:


新建一个空项目,然后添加一个试图控制器ViewController.m,继承UIViewController,然后指定跟视图控制器:

ViewController.m:

#import "ViewController.h"@interface ViewController ()@property(strong,nonatomic)  UITextField *textField;@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];    //创建界面UI    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 40, 80, 40)];    [label setText:@"生日:"];    [self.view addSubview:label];    //UITextField    UITextField *birthdayText = [[UITextField alloc]initWithFrame:CGRectMake(100, 40, 200, 40)];    [birthdayText setPlaceholder:@"请输入生日"];    [birthdayText setBorderStyle:UITextBorderStyleRoundedRect];    [birthdayText setEnabled:YES];//禁止编辑        [self.view addSubview:birthdayText];    _textField = birthdayText;//self.textField = _textField        //添加日期控件    UIDatePicker *datePicker = [[UIDatePicker alloc]init];//frame指定不指定结果一样    [birthdayText setInputView:datePicker];        [datePicker setDatePickerMode:UIDatePickerModeDate];//    NSLog(@"%@",[NSLocale availableLocaleIdentifiers]);    [datePicker setLocale:[NSLocale localeWithLocaleIdentifier:@"zh_Hans_CN"]];        //设置生日文本输入时使用的试图    [datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];    //设置日期控件初始值    //4.1 指定字符串    NSString *beforeString = @"1993-02-02";    //4.2 字符串转化成日期    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];    [inputFormatter setDateFormat:@"yyyy-MM-dd"];    NSDate* inputDate = [inputFormatter dateFromString:beforeString];    //4.3 转化后字符串给日期选择控件    [datePicker setDate:inputDate animated:YES];}#pragma mark -日期选择器的监听方法-(void) dateChanged:(UIDatePicker *)datePicker{    NSDate *date = datePicker.date;        //设计日期格式     NSDateFormatter *formatter = [[NSDateFormatter alloc]init];    //设置日期格式    [formatter setDateFormat:@"yyyy-MM-dd"];    NSString *str = [formatter stringFromDate:date];    [_textField setText:str];}@end

NSDateFormatter主要是为了将选择的日期按照我们规定的格式显示出来,

1993年2月2日   -》  yyyy-MM-dd   -》 1993-02-02

还有一点需要注意,当我们不知道datePicker显示的格式时,我们可以把所有的格式打印出来找自己觉得比较像的,比如说zh(中),这种一个个试试,好的程序是改出来的,不要怕失败




0 0
原创粉丝点击