UIKit框架-高级控件:4.UIDatePickerView的基本认识

前面我们学完了第一个高级控件UIScrollView, 这个控件的确有很多很强大的功能, 其中一个就是可以实现我们的跑马灯, 在一些新闻客户端里面, 里面会有图片每隔一段时间就会自动跳转, 其实这里面就是UIScrollView, 这个功能就让大家自己去完成了, 现在让我们来看看第二个高级控件UIPickerView.



1.添加全局变量

@interface ViewController ()

@property (strong, nonatomic) UITextField *birthdayText;

@end


2.添加UILabel

#pragma mark 添加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.添加UIDatePicker的监听方法

- (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];
}



5.最后在viewDidLoad里实现

- (void)viewDidLoad {
    [super viewDidLoad];
    [self myLabel];
    [self myDatePicker];
}


6.最终效果:

 

posted @ 2015-03-01 22:09  背着吉他去流浪  阅读(314)  评论(0编辑  收藏  举报