ios 自定义时间选择器

typedef NS_ENUM(NSInteger, UIDatePickerMode) {
    UIDatePickerModeTime,           // Displays hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. 6 | 53 | PM)
    UIDatePickerModeDate,           // Displays month, day, and year depending on the locale setting (e.g. November | 15 | 2007)
    UIDatePickerModeDateAndTime,    // Displays date, hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. Wed Nov 15 | 6 | 53 | PM)
    UIDatePickerModeCountDownTimer, // Displays hour and minute (e.g. 1 | 53)
}

官方的UIDatePicker只有四种模式,不能选到秒。
变态的需求必须要精确到秒,就自定义了一个。

思路

定义多个UIPickerView,用来选择年-月-日 时:分:秒。注意tag区分每个pickerView,设置好dataSource和delegate
每个pickerView显示1个component,多行row供选择。

.h

#import <UIKit/UIKit.h>

@protocol WJDatePickerDelegate;
@interface WJDatePicker : UIView

@property (nonatomic, retain) NSDate*   date;       // 当前date
@property (nonatomic, strong) NSString* dateString;

/**
 * 设置默认值为当前时间
 */
-(void)resetDateToCurrentDate;

/**
 * 设置提示信息
 */
-(void)setHintsText:(NSString*)hints;
/**
 * 点击确定按钮
 */
-(IBAction)actionEnter:(id)sender;
@property (nonatomic, assign) id<WJDatePickerDelegate>delegate;
@end

@protocol WJDatePickerDelegate <NSObject>
/**
 * 代理  点击确定后的事件
 */
@optional
-(void)DatePickerDelegateEnterActionWithDataPicker:(WJDatePicker*)picker;
@end

.m实现

#import "WJDatePicker.h"
#import "NSDate+FSExtension.h"

typedef enum {
    ePickerViewTagYear = 2016,
    ePickerViewTagMonth,
    ePickerViewTagDay,
    ePickerViewTagHour,
    ePickerViewTagMinute,
    ePickerViewTagSecond
}PickViewTag;

@interface WJDatePicker () <UIPickerViewDataSource,UIPickerViewDelegate>
@property (nonatomic, retain) UIPickerView* yearPicker;     // 年
@property (nonatomic, retain) UIPickerView* monthPicker;    // 月
@property (nonatomic, retain) UIPickerView* dayPicker;      // 日
@property (nonatomic, retain) UIPickerView* hourPicker;     // 时
@property (nonatomic, retain) UIPickerView* minutePicker;   // 分
@property (nonatomic, retain) UIPickerView* secondPicker;

@property (nonatomic, retain) UIToolbar*    toolBar;        // 工具条
@property (nonatomic, retain) UILabel*      hintsLabel;     // 提示信息

// dataSource
@property (nonatomic, retain) NSMutableArray* yearArray;
@property (nonatomic, retain) NSMutableArray* monthArray;
@property (nonatomic, retain) NSMutableArray* dayArray;
@property (nonatomic, retain) NSMutableArray* hourArray;
@property (nonatomic, retain) NSMutableArray* minuteArray;
@property (nonatomic, retain) NSMutableArray* secondArray;

@property (nonatomic, assign) NSUInteger yearValue;
@property (nonatomic, assign) NSUInteger monthValue;
@property (nonatomic, assign) NSUInteger dayValue;
@property (nonatomic, assign) NSUInteger hourValue;
@property (nonatomic, assign) NSUInteger minuteValue;
@property (nonatomic, assign) NSUInteger secondValue;

/**
 * 创建数据源
 */
-(void)createDataSource;

/**
 * create month Arrays
 */
-(void)createMonthArrayWithYear:(NSInteger)yearInt month:(NSInteger)monthInt;
@end

@implementation WJDatePicker

@synthesize delegate;
@synthesize date;

#pragma mark -
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:CGRectMake(0, 0, 440, 260)];
    if (self) {
        // Initialization code
        [self setBackgroundColor:[UIColor whiteColor]];
        self.yearArray = [[NSMutableArray alloc]initWithCapacity:0];
        self.monthArray = [[NSMutableArray alloc]initWithCapacity:0];
        self.dayArray = [[NSMutableArray alloc]initWithCapacity:0];
        self.hourArray = [[NSMutableArray alloc]initWithCapacity:0];
        self.minuteArray = [[NSMutableArray alloc]initWithCapacity:0];
        self.secondArray = [[NSMutableArray alloc]initWithCapacity:0];
        
        // 更新数据源
        [self createDataSource];
        
        // 创建 toolBar & hintsLabel & enter button
        self.toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 44)];
        [self.toolBar setBackgroundColor:[UIColor blueColor]];
        [self addSubview:self.toolBar];
        
//        UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        cancleBtn.frame = CGRectMake(0, 5, (self.frame.size.width-200)/2, 34);
//        [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
//        [cancleBtn addTarget:self action:@selector(actionCancle:) forControlEvents:UIControlEventTouchUpInside];
//        [self.toolBar addSubview:cancleBtn];
        
        self.hintsLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.frame.size.width-200)/2, 5, 200, 34)];
        self.hintsLabel.textAlignment = NSTextAlignmentCenter;
        [self.hintsLabel setFont:[UIFont systemFontOfSize:15.0f]];
        [self.hintsLabel setTextColor:[UIColor whiteColor]];
        [self.toolBar addSubview:self.hintsLabel];
        
        UIButton* tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [tempBtn setTitle:@"确定" forState:UIControlStateNormal];
        tempBtn.frame = CGRectMake(CGRectGetMaxX(_hintsLabel.frame), 5, (self.frame.size.width-200)/2, 34);
        [tempBtn addTarget:self action:@selector(actionEnter:) forControlEvents:UIControlEventTouchUpInside];
        [self.toolBar addSubview:tempBtn];
        
        NSArray *titles = @[@"月",@"日",@"时",@"分"];
        // 初始化各个视图
        self.yearPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 44, 80, 216)];
        self.monthPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(81, 44, 60, 216)];
        self.dayPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(156, 44, 60, 216)];
        self.hourPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(231, 44, 60, 216)];
        self.minutePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(306, 44, 60, 216)];
        self.secondPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(381, 44, 60, 216)];
        
        for (NSInteger i=0; i<titles.count; i++) {
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(141+75*i, 139, 15, 26)];
//            label.backgroundColor = [UIColor orangeColor];
            label.textColor = [UIColor blackColor];
            label.text = titles[i];
            [self addSubview:label];
        }
        
        [self.yearPicker setDataSource:self];
        [self.monthPicker setDataSource:self];
        [self.dayPicker setDataSource:self];
        [self.hourPicker setDataSource:self];
        [self.minutePicker setDataSource:self];
        [self.secondPicker setDataSource:self];
        
        [self.yearPicker setDelegate:self];
        [self.monthPicker setDelegate:self];
        [self.dayPicker setDelegate:self];
        [self.hourPicker setDelegate:self];
        [self.minutePicker setDelegate:self];
        [self.secondPicker setDelegate:self];
        
        [self.yearPicker setTag:ePickerViewTagYear];
        [self.monthPicker setTag:ePickerViewTagMonth];
        [self.dayPicker setTag:ePickerViewTagDay];
        [self.hourPicker setTag:ePickerViewTagHour];
        [self.minutePicker setTag:ePickerViewTagMinute];
        [self.secondPicker setTag:ePickerViewTagSecond];
        
        [self addSubview:self.yearPicker];
        [self addSubview:self.monthPicker];
        [self addSubview:self.dayPicker];
        [self addSubview:self.hourPicker];
        [self addSubview:self.minutePicker];
        [self addSubview:self.secondPicker];
        
        [self.yearPicker setShowsSelectionIndicator:YES];
        [self.monthPicker setShowsSelectionIndicator:YES];
        [self.dayPicker setShowsSelectionIndicator:YES];
        [self.hourPicker setShowsSelectionIndicator:YES];
        [self.minutePicker setShowsSelectionIndicator:YES];
        [self.secondPicker setShowsSelectionIndicator:YES];
        
        [self resetDateToCurrentDate];
    }
    return self;
}
#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (ePickerViewTagYear == pickerView.tag) {
        return [self.yearArray count];
    }
    
    if (ePickerViewTagMonth == pickerView.tag) {
        return [self.monthArray count];
    }
    
    if (ePickerViewTagDay == pickerView.tag) {
        return [self.dayArray count];
    }
    
    if (ePickerViewTagHour == pickerView.tag) {
        return [self.hourArray count];
    }
    
    if (ePickerViewTagMinute == pickerView.tag) {
        return [self.minuteArray count];
    }
    if (ePickerViewTagSecond == pickerView.tag) {
        return [self.secondArray count];
    }
    return 0;
}
#pragma makr - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (ePickerViewTagYear == pickerView.tag) {
        return [self.yearArray objectAtIndex:row];
    }
    
    if (ePickerViewTagMonth == pickerView.tag) {
        return [self.monthArray objectAtIndex:row];
    }
    
    if (ePickerViewTagDay == pickerView.tag) {
        return [self.dayArray objectAtIndex:row];
    }
    
    if (ePickerViewTagHour == pickerView.tag) {
        return [self.hourArray objectAtIndex:row];
    }
    
    if (ePickerViewTagMinute == pickerView.tag) {
        return [self.minuteArray objectAtIndex:row];
    }
    if (ePickerViewTagSecond == pickerView.tag) {
        return [self.secondArray objectAtIndex:row];
    }
    return @"";
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (ePickerViewTagYear == pickerView.tag) {
        self.yearValue = [[self.yearArray objectAtIndex:row] intValue];
    } else if(ePickerViewTagMonth == pickerView.tag){
        self.monthValue = [[self.monthArray objectAtIndex:row] intValue];
    } else if(ePickerViewTagDay == pickerView.tag){
        self.dayValue = [[self.dayArray objectAtIndex:row]intValue];
    } else if(ePickerViewTagHour == pickerView.tag){
        self.hourValue = [[self.hourArray objectAtIndex:row]intValue];
    } else if(ePickerViewTagMinute == pickerView.tag){
        self.minuteValue = [[self.minuteArray objectAtIndex:row] intValue];
    } else if(ePickerViewTagSecond == pickerView.tag){
        self.secondValue = [[self.secondArray objectAtIndex:row] intValue];
    }
    if (ePickerViewTagMonth == pickerView.tag || ePickerViewTagYear == pickerView.tag) {
        [self createMonthArrayWithYear:self.yearValue month:self.monthValue];
        [self.dayPicker reloadAllComponents];
    }
    
    self.dateString = [NSString stringWithFormat:@"%04lu-%02lu-%02lu %02lu:%02lu:%02lu",self.yearValue, self.monthValue, self.dayValue, self.hourValue, self.minuteValue,self.secondValue];
    [self setDate:[NSDate fs_dateFromString:self.dateString format:@"yyyy-MM-dd HH:mm:ss"]];
}
#pragma mark - 年月日闰年=情况分析
/**
 * 创建数据源
 */
-(void)createDataSource{
    // 年
    NSInteger yearInt = [[NSDate date] fs_year];
    [self.yearArray removeAllObjects];
    for (NSInteger i=yearInt; i<=yearInt+5; i++) {
        [self.yearArray addObject:[NSString stringWithFormat:@"%ld",(long)i]];
    }
    
    // 月
    [self.monthArray removeAllObjects];
    for (int i=1; i<=12; i++) {
        [self.monthArray addObject:[NSString stringWithFormat:@"%d",i]];
    }
    
    
    NSInteger month = [[NSDate date] fs_month];
    
    [self createMonthArrayWithYear:yearInt month:month];
    
    // 时
    [self.hourArray removeAllObjects];
    for(int i=0; i<24; i++){
        [self.hourArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
    
    // 分
    [self.minuteArray removeAllObjects];
    for(int i=0; i<60; i++){
        [self.minuteArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
    
    // 秒
    [self.secondArray removeAllObjects];
    for(int i=0; i<60; i++){
        [self.secondArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
}
#pragma mark -
-(void)resetDateToCurrentDate{
    NSDate* nowDate = [NSDate date];
    [self.yearPicker selectRow:0 inComponent:0 animated:YES];
    [self.monthPicker selectRow:[nowDate fs_month]-1 inComponent:0 animated:YES];
    [self.dayPicker selectRow:[nowDate fs_day]-1 inComponent:0 animated:YES];
    
    [self.hourPicker selectRow:[nowDate fs_hour] inComponent:0 animated:YES];
    [self.minutePicker selectRow:[nowDate fs_minute] inComponent:0 animated:YES];
    [self.secondPicker selectRow:[nowDate fs_second] inComponent:0 animated:YES];
    
    [self setYearValue:[nowDate fs_year]];
    [self setMonthValue:[nowDate fs_month]];
    [self setDayValue:[nowDate fs_day]];
    [self setHourValue:[nowDate fs_hour]];
    [self setMinuteValue:[nowDate fs_minute]];
    [self setSecondValue:[nowDate fs_second]];
    
    self.dateString = [NSString stringWithFormat:@"%04lu-%02lu-%02lu %02lu:%02lu:%02lu",self.yearValue, self.monthValue, self.dayValue, self.hourValue, self.minuteValue, self.secondValue];
    [self setDate:[NSDate fs_dateFromString:self.dateString format:@"yyyy-MM-dd HH:mm:ss"]];
}
#pragma mark -
-(void)createMonthArrayWithYear:(NSInteger)yearInt month:(NSInteger)monthInt{
    int endDate = 0;
    switch (monthInt) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            endDate = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            endDate = 30;
            break;
        case 2:
            // 是否为闰年
            if (yearInt % 400 == 0) {
                endDate = 29;
            } else {
                if (yearInt % 100 != 0 && yearInt %4 ==4) {
                    endDate = 29;
                } else {
                    endDate = 28;
                }
            }
            break;
        default:
            break;
    }
    
    if (self.dayValue > endDate) {
        self.dayValue = endDate;
    }
    // 日
    [self.dayArray removeAllObjects];
    for(int i=1; i<=endDate; i++){
        [self.dayArray addObject:[NSString stringWithFormat:@"%d",i]];
    }
}
#pragma mark - 点击确定按钮
-(IBAction)actionEnter:(id)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(DatePickerDelegateEnterActionWithDataPicker:)]) {
        [self.delegate DatePickerDelegateEnterActionWithDataPicker:self];
    }
    [self removeFromSuperview];
}

//- (void)actionCancle:(UIButton *)btn{
//   [self removeFromSuperview];
//}
#pragma mark - 设置提示信息
-(void)setHintsText:(NSString*)hints{
    [self.hintsLabel setText:hints];
}
#pragma mark -
-(void)removeFromSuperview{
    self.delegate = nil;
    [super removeFromSuperview];
}
@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容

  • UIPickerView也是一个选择器控件,它比UIDatePicker更加通用,它可以生成单列的选择器,也可生成...
    小蘑菇2阅读 3,496评论 3 5
  • 前序 在阅读公司项目代码的时候发现使用到了五级的时间选择器,当时是使用一个UIDatePicker和一个两级的UI...
    KingTortoise阅读 3,446评论 1 4
  • 因项目需求,需要用到一个时间选择器,设置最大可选时间与最小可选时间,其它无效不可选的时间需要‘干’掉!!!苦于找了...
    hello_bear阅读 4,537评论 3 5
  • 先上效果图 之前项目中要用到时间选择器,时间比较紧就大概写了个,凑合能用。闲下来了,这几天把这个重新写了下。大家可...
    WKCaesar阅读 2,462评论 0 2
  • UIPickerView 继承了UIView 没有继承UIControl UIPickerView的时间处理由其委...
    nalis风阅读 1,457评论 0 0