UIKit框架-高级控件:5.UIDatePickerView日期选择

来源:互联网 发布:mac用itunes制作铃声 编辑:程序博客网 时间:2024/05/17 01:28

在前面, 我们对UIScrollView有了基本的认识和基本使用, 现在我们来学习第二个高级控件UIPickerView, 废话不多说, 现在让我们来看看怎么使用.


1.定义全局变量

@interface ViewController ()@property (strong, nonatomic) UITextField *birthdayText;@end

PS: 其实全局变量也可以定义成属性, 这样子会更加的方便.



2.添加UILabel

- (void)myLabel{    // 1.添加label    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20.0, 20.0, 80.0, 40.0)];    [label setText:@"生日 : "];    [self.view addSubview:label];        // 2.实例化TextField    _birthdayText = [[UITextField alloc] initWithFrame:CGRectMake(100.0, 20, 200.0, 40.0)];    [_birthdayText setPlaceholder:@"请选择日期"];    [_birthdayText setBorderStyle:UITextBorderStyleRoundedRect];    [self.view addSubview:_birthdayText];}



3.添加UIDatePicker

- (void)myDatePicker{    // 1.日期Picker    UIDatePicker *datePickr = [[UIDatePicker alloc] init];    // 1.1选择datePickr的显示风格    [datePickr setDatePickerMode:UIDatePickerModeDate];        // 1.2查询所有可用的地区    //NSLog(@"%@", [NSLocale availableLocaleIdentifiers]);        // 1.3设置datePickr的地区语言, zh_Han后面是s的就为简体中文,zh_Han后面是t的就为繁体中文    [datePickr setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_Hans_CN"]];        // 1.4监听datePickr的数值变化    [datePickr addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];        // 2.设置日期控件的初始值    // 2.1 指定一个字符串    NSString *dateString = @"1949-10-1";        // 2.2 把字符串转换成日期    NSDateFormatter *fromatter = [[NSDateFormatter alloc] init];    [fromatter setDateFormat:@"yyyy-MM-dd"];    NSDate *date = [fromatter dateFromString:dateString];        // 2.3 将转换后的日期设置给日期选择控件    [datePickr setDate:date];        // 3.设置PickerView为birthdayText输入控件    [_birthdayText setInputView:datePickr];}



4.添加DatePicker的监听方法
#pragma mark DatePicker监听方法- (void)dateChanged:(UIDatePicker *)datePicker{    // 1.要转换日期格式, 必须得用到NSDateFormatter, 专门用来转换日期格式    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];        // 1.1 先设置日期的格式字符串    [formatter setDateFormat:@"yyyy-MM-dd"];        // 1.2 使用格式字符串, 将日期转换成字符串    NSString *dateString = [formatter stringFromDate:datePicker.date];    // 2.把Date添加到文本    [_birthdayText setText:dateString];}

PS: 注意, 如果要把字符串转成日期, 或者把日期转成字符串, 必须得以NSDateFormatter作为媒介, 然后才可以实现.



最终效果:

 

 



好了, 这次我们就讲到这里, 下次我们继续~~~

0 0