UIDatePicker基本使用

UIDatePicker提供了一個快速選擇日期和時間的控件,他是UIControl的子類,專門用於日期時間的選擇。其樣式能夠經過UIDatePicker的屬性進行靈活設置,同時也能夠獲取到當前UIDatePicker的值。UIDatePicker有幾個方法和屬性須要重點掌握。ide

 

@property (nonatomic) UIDatePickerMode datePickerMode; //設置UIDatePicker的展現樣式,有四種樣式atom

    UIDatePickerModeTime,           // 僅顯示時間
    UIDatePickerModeDate,           // 顯示年月日
    UIDatePickerModeDateAndTime,    // 顯示年月日和時間
    UIDatePickerModeCountDownTimer  //倒計時spa


@property (nullable, nonatomic, strong) NSLocale   *locale;   //設置地區,地區的設置會影響日期以及時間文字的展現方式

@property (nullable, nonatomic, strong) NSTimeZone *timeZone; //設置時區code


@property (nonatomic, strong) NSDate *date; //獲取當前日期/時間值orm

 

- (void)setDate:(NSDate *)date animated:(BOOL)animated;//設置當前顯示的日期時間blog

 

下面來看一個完整示例,選擇時間後點擊肯定按鈕會彈出提示框,提示框內容爲選擇的時間字符串

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,strong)UIDatePicker *datePicker;
@property(nonatomic,strong)UIButton *button;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.datePicker];
    [self.view addSubview:self.button];
}

//懶加載
- (UIDatePicker *)datePicker{
    if (_datePicker == nil) {
        self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 280, self.view.frame.size.width, 200)];
        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        _datePicker.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    }
    return _datePicker;
}

//懶加載按鈕,用於展現datePicker選中的時間
- (UIButton *)button{
    if (_button == nil) {
        self.button = [[UIButton alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 50) / 2.0, 100, 50, 30)];
        [_button setTitle:@"肯定" forState:UIControlStateNormal];
        _button.backgroundColor = [UIColor blueColor];
        [_button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button;
}

//肯定按鈕被點擊
- (void)clickButton{
    //獲取用戶經過UIDatePicker設置的時間
    NSDate *date = [self.datePicker date];
    
    //建立一個日期格式器
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    //爲日期格式器設置格式字符串
    [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm +0800"];
    //使用日期格式器格式化日期和時間
    NSString *dateString = [dateFormatter stringFromDate:date];
    NSString *message = [NSString stringWithFormat:@"您選擇的日期和時間是:%@",dateString];
    
    //警告框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"日期和時間" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:nil];
    
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:nil];
}

@end

運行截圖:get

相關文章
相關標籤/搜索