iphone开发UI组件之UIDatePicker日期选择组件的预习

 为了省时间,直接上代码吧。

新建工程。

编辑控制器的.h文件如下:

//
//  ViewController.h
//  datepicker
//
//  Created by apple on 15/9/2.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) UILabel *dateLabel;
@end

编辑控制器的.m文件如下:

//
//  ViewController.m
//  datepicker
//
//  Created by apple on 15/9/2.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//

#import "ViewController.h"
#define  WIDTH    [UIScreen mainScreen].bounds.size.width
#define  HEIGHT  [UIScreen mainScreen].bounds.size.height

@interface ViewController ()

@end

@implementation ViewController

-(NSDate *) stringToDate:(NSString *)timeStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [formatter dateFromString:timeStr];
}

-(NSString *)dateToString:(NSDate *)timeDate
{

    NSDateFormatter *formatter = [[NSDateFormatter alloc]  init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    return [formatter stringFromDate:timeDate];
}

-(void)initDatePicker
{
    self.datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(20, 20, (WIDTH-20)/2, (WIDTH-20)/2)];
    self.datePicker.datePickerMode = UIDatePickerModeDate;
    self.datePicker.minuteInterval = 5;
    self.datePicker.minimumDate = [self stringToDate:@"1990-01-01 00:00:00"];
    self.datePicker.maximumDate = [self stringToDate:@"2015-08-01 00:00:00"];
    self.datePicker.date = [NSDate date];
    [self.datePicker addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:self.datePicker];
}

-(void) initDateLabel
{
    self.dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, (WIDTH-20)/2+30, WIDTH, 50)];
    self.dateLabel.textAlignment = NSTextAlignmentCenter;
    self.dateLabel.backgroundColor = [UIColor clearColor];
    self.dateLabel.font = [UIFont systemFontOfSize:21.0];
    [self.view addSubview:self.dateLabel];
}

-(void) valueChanged:(UIDatePicker *)sender
{
    self.dateLabel.text = [self dateToString:sender.date];

}



- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initDatePicker];
    [self initDateLabel];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
运行结果如下:




你可能感兴趣的:(iphone开发UI组件之UIDatePicker日期选择组件的预习)