iOS 年月日选择器

1、创建一个集成PickerView的View

.h文件

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface LYDateIntervalSelectorPicker : UIPickerView<UIPickerViewDelegate, UIPickerViewDataSource>

-(instancetype)initWithDatePickerView;

@property (nonatomic, strong, readonly) NSDate *date;

@end

NS_ASSUME_NONNULL_END

.m文件

#import "LYDateIntervalSelectorPicker.h"

static CGFloat rowsHeight = 44.0;

@interface LYDateIntervalSelectorPicker ()

@property (nonatomic, strong) NSIndexPath *todayIndexPath;
@property (nonatomic, strong) NSArray *months;
@property (nonatomic, strong) NSArray *years;
@property (nonatomic, strong) NSArray *days;
@property (nonatomic, strong) NSCalendar *calendar;

@end

@implementation LYDateIntervalSelectorPicker

-(instancetype)initWithDatePickerView{
    
    self = [super init];
    if (self) {
        
        self.delegate = self;
        self.dataSource = self;
        
        self.years = [self nameOfYears];
        self.months = [self nameOfMonths];
        self.days = [self nameOfDays];
        self.todayIndexPath = [self todayPath];
        [self selectCurrentDate];
        
    }
    return self;
    
}

- (void)selectCurrentDate{
    
    NSIndexPath *selectIndexPath = [self todayPath];
    
    //设置当前年份
    [self selectRow:selectIndexPath.section
        inComponent:0
           animated:YES];
    [self pickerView:self didSelectRow:selectIndexPath.row inComponent:0];
    
    selectIndexPath = [self todayPath];
    
    //设置当前月份
    [self selectRow:selectIndexPath.row
        inComponent:1
           animated:YES];
    [self pickerView:self didSelectRow:selectIndexPath.row inComponent:1];
    
    //设置当前日期
    CGFloat day = [[[self currentDayName] substringToIndex:[self currentDayName].length] floatValue] - 1;
    [self selectRow:day inComponent:2 animated:YES];
    [self pickerView:self didSelectRow:day inComponent:2];
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    //获取当前选中的是几号
    NSInteger currert = [pickerView selectedRowInComponent:2] + 1;
    
    //判断二月份最大天数和30号和31号
    if (currert > [self daysCountWithSelectDate]) {
        [pickerView selectRow:[self daysCountWithSelectDate] inComponent:2 animated:NO];
    }
    
    if (component == 0 || component == 1) {
        self.days = [self nameOfDays];
        [pickerView reloadComponent:1];
        [pickerView reloadComponent:2];
    }
    
}

-(NSDate *)date{

    NSString *year = [self.years objectAtIndex:([self selectedRowInComponent:0])];
    NSString *month = [self.months objectAtIndex:([self selectedRowInComponent:1])];
    NSString *day = [self.days objectAtIndex:([self selectedRowInComponent:2]) % self.days.count];

    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy年M月d日"];
    NSString *dateString = [NSString stringWithFormat:@"%@%@%@", year, month, day];
    NSDate *date = [formatter dateFromString:dateString];
    return date;

}

#pragma mark - UIPickerViewDelegate

-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    return [self componentWidth];
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

    UILabel *returnView = [self labelForComponent:component];
    returnView.text = [self titleForRow:row forComponent:component];
    return returnView;
    
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return rowsHeight;
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    if(component == 0){
        return self.years.count;
    }else if (component == 1) {
        return self.months.count;
    }else {
        return self.days.count;
    }
    
}

-(CGFloat)componentWidth{
    return self.bounds.size.width / 3;
}

-(NSString *)titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if(component == 0) {
        return [self.years objectAtIndex:(row)];
    }else if(component == 1) {
        return [self.months objectAtIndex:(row)];
    }else {
        NSInteger DayCount = self.days.count;
        return [self.days objectAtIndex:(row % DayCount)];
    }
    
}

-(UILabel *)labelForComponent:(NSInteger)component{
    
    CGRect frame = CGRectMake(0, 0, [self componentWidth], rowsHeight);
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    label.userInteractionEnabled = NO;
    return label;
    
}



#pragma mark --------- 华丽的分割线 ---------



//当前时间
-(NSIndexPath *)todayPath{
    
    CGFloat row = 0.f;
    CGFloat section = 0.f;
    
    NSString *year  = [self currentYearName];
    NSString *month = [self currentMonthName];
    
    for(NSString *cellYear in self.years) {
        
        if([cellYear isEqualToString:year]) {
            section = [self.years indexOfObject:cellYear];
            break;
        }
        
    }
    
    for(NSString *cellMonth in self.months) {
        
        if([cellMonth isEqualToString:month]) {
            row = [self.months indexOfObject:cellMonth];
            break;
        }
        
    }
    
    return [NSIndexPath indexPathForRow:row inSection:section];
    
}

//年份数组
-(NSArray *)nameOfYears{
    
    NSMutableArray *years = [NSMutableArray array];
    NSInteger currentYear = [[[self currentYearName] substringToIndex:4] integerValue];
    
    for(NSInteger year = currentYear - 5; year <= currentYear; year++) {
        NSString *yearStr = [NSString stringWithFormat:@"%li年", (long)year];
        [years addObject:yearStr];
    }
    return years;
    
}

//月份数组
-(NSArray *)nameOfMonths{
    return @[@"1月", @"2月", @"3月", @"4月", @"5月", @"6月", @"7月", @"8月", @"9月", @"10月", @"11月", @"12月"];
}

//日期数组
-(NSArray *)nameOfDays{
    
    NSUInteger numberOfDaysInMonth = [self daysCountWithSelectDate];
    NSMutableArray *tempArr = [NSMutableArray array];
    for (int i = 1; i < numberOfDaysInMonth + 1 ; i ++) {
        NSString *day = [NSString stringWithFormat:@"%d日",i];
        [tempArr addObject:day];
    }
    return tempArr;
    
}

//根据当前年月获取当前月天数
-(NSInteger)daysCountWithSelectDate{
    self.calendar = [NSCalendar currentCalendar];
    NSRange range = [self.calendar rangeOfUnit:NSCalendarUnitDay
                                        inUnit:NSCalendarUnitMonth
                                       forDate:[self monthDate]];
    return range.length;
}

//根据当前年月返回日期
-(NSDate *)monthDate{
    
    NSString *year = [self.years objectAtIndex:([self selectedRowInComponent:0])];
    NSString *month = [self.months objectAtIndex:([self selectedRowInComponent:1])];
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy年M月"];
    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%@%@", year, month]];
    return date;
    
}

//当前年份
-(NSString *)currentYearName{
    
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy年"];
    return [formatter stringFromDate:[NSDate date]];
    
}

//当前月份
-(NSString *)currentMonthName{
    
    NSDateFormatter *formatter = [NSDateFormatter new];
    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [formatter setLocale:usLocale];
    [formatter setDateFormat:@"M月"];
    return [formatter stringFromDate:[NSDate date]];
    
}

//当前日期
-(NSString *)currentDayName{
    
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"d日"];
    return [formatter stringFromDate:[NSDate date]];
    
}

@end

2、创建一个View

.h文件

#import <UIKit/UIKit.h>
#import "LYDateIntervalSelectorPicker.h"

NS_ASSUME_NONNULL_BEGIN

@interface LYDateIntervalSelectorView : UIView

//单例
+(LYDateIntervalSelectorView *)initClient;

-(void)datePickerCompleteBlock:(void (^)(NSDate *date))completeBlock;

@end

NS_ASSUME_NONNULL_END

.m文件 — 引入头文件
#import "LYDateIntervalSelectorPicker.h"

#import "LYDateIntervalSelectorView.h"
#import "LYDateIntervalSelectorPicker.h"

static CGFloat whiteViewHeight = 400.f;
static CGFloat pickerHeight = 250.f;

//时间回调
typedef void (^ DateBlock)(NSDate *);

@interface LYDateIntervalSelectorView ()
{
    CGFloat height;
    CGFloat width;
}

//白色背景
@property (nonatomic, strong) UIView *whiteView;

@property (nonatomic, copy) DateBlock dateBlock;

//选择器
@property (nonatomic, strong) LYDateIntervalSelectorPicker *selectorPicker;

@end

@implementation LYDateIntervalSelectorView

+(LYDateIntervalSelectorView *)initClient{
    
    static LYDateIntervalSelectorView *client = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        client = [[self alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [client createUI];
    });
    return client;
    
}

-(void)datePickerCompleteBlock:(void (^)(NSDate *date))completeBlock{
    
    _dateBlock = completeBlock;
    [self show];
    
}

#pragma mark - 创建布局
-(void)createUI{
    
    height = [UIScreen mainScreen].bounds.size.height;
    width = [UIScreen mainScreen].bounds.size.width;
    
    //取消手势
    UITapGestureRecognizer *cancelTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapCancelAction)];
    [self addGestureRecognizer:cancelTap];
    
    //白色背景
    self.whiteView = [[UIView alloc]initWithFrame:CGRectMake(0, height, width, whiteViewHeight)];
    self.whiteView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.whiteView];
    
    //完成
    UIButton *bConfirm = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, width, 40)];
    [bConfirm setTitle:@"完成" forState:0];
    [bConfirm setTitleColor:[UIColor cyanColor] forState:0];
    [bConfirm addTarget:self action:@selector(buttonConfirm) forControlEvents:UIControlEventTouchUpInside];
    [self.whiteView addSubview:bConfirm];
    
    //选择器
    self.selectorPicker = [[LYDateIntervalSelectorPicker alloc]initWithDatePickerView];
    self.selectorPicker.frame = CGRectMake(0, whiteViewHeight - pickerHeight, width, pickerHeight);
    [self.whiteView addSubview:self.selectorPicker];
    
    
}

-(void)buttonConfirm{
    
    if (_dateBlock) {
        _dateBlock(_selectorPicker.date);
    }
    
}

//显示手势
-(void)show{
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    [UIView animateWithDuration:0.25 animations:^{
        self.whiteView.frame = CGRectMake(0, self->height - whiteViewHeight, self->width, whiteViewHeight);
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    }];
    
}

//取消手势
-(void)tapCancelAction{
    
    [UIView animateWithDuration:0.2 animations:^{
        self.whiteView.frame = CGRectMake(0, self->height, self->width, whiteViewHeight);
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
    
}

@end

3、创建一个Controller

.h文件

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface DateSelectorController : UIViewController

@end

NS_ASSUME_NONNULL_END

.m文件 —— 引入头文件
#import "LYDateIntervalSelectorView.h"

#import "DateSelectorController.h"
#import "LYDateIntervalSelectorView.h"

@interface DateSelectorController ()

@end

@implementation DateSelectorController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [[LYDateIntervalSelectorView initClient] datePickerCompleteBlock:^(NSDate * _Nonnull date) {
        
        NSString *formatStr = @"yyyy年MM月dd日";
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:formatStr];
        NSLog(@"%@",[dateFormatter stringFromDate:date]);
        
    }];
    
}

@end

4、效果图

效果图.gif

5、全剧终

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

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,081评论 1 32
  • 废话不多说,直接上干货 ---------------------------------------------...
    小小赵纸农阅读 3,326评论 0 15
  • 原文: iOS应用架构谈 view层的组织和调用方案 iOS应用架构谈 开篇 iOS应用架构谈 网络层设计方案 i...
    难却却阅读 1,250评论 0 7
  • 又是晚上我的手里拽着大半个月亮你在人间推开了窗 一颗凡心在动你在遥远的黑夜里长叹:天若有情,月如无恨 一片光脱了缰...
    2020号阅读 367评论 29 22
  • 第二章 我还记得,在机场过夜的时候发生了很多奇怪的事情,为什么奇怪呢,从何说起呢?当然是要从我10号晚上到上海机场...
    光芒万丈_阅读 241评论 0 0