UIKit框架-高級控件:5.UIDatePickerView日期選擇

在前面, 咱們對UIScrollView有了基本的認識和基本使用, 如今咱們來學習第二個高級控件UIPickerView, 廢話很少說, 如今讓咱們來看看怎麼使用.學習


1.定義全局變量atom

@interface ViewController ()

@property (strong, nonatomic) UITextField *birthdayText;

@end

PS: 其實全局變量也能夠定義成屬性, 這樣子會更加的方便.spa



2.添加UILabel
code

- (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做爲媒介, 而後才能夠實現.



最終效果:orm

 

 



好了, 此次咱們就講到這裏, 下次咱們繼續~~~字符串

相關文章
相關標籤/搜索