iOS 年月日選擇器

1锣吼、創(chuàng)建一個(gè)集成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];
    
    //設(shè)置當(dāng)前年份
    [self selectRow:selectIndexPath.section
        inComponent:0
           animated:YES];
    [self pickerView:self didSelectRow:selectIndexPath.row inComponent:0];
    
    selectIndexPath = [self todayPath];
    
    //設(shè)置當(dāng)前月份
    [self selectRow:selectIndexPath.row
        inComponent:1
           animated:YES];
    [self pickerView:self didSelectRow:selectIndexPath.row inComponent:1];
    
    //設(shè)置當(dāng)前日期
    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{
    
    //獲取當(dāng)前選中的是幾號(hào)
    NSInteger currert = [pickerView selectedRowInComponent:2] + 1;
    
    //判斷二月份最大天數(shù)和30號(hào)和31號(hào)
    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 --------- 華麗的分割線 ---------



//當(dāng)前時(shí)間
-(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];
    
}

//年份數(shù)組
-(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;
    
}

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

//日期數(shù)組
-(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;
    
}

//根據(jù)當(dāng)前年月獲取當(dāng)前月天數(shù)
-(NSInteger)daysCountWithSelectDate{
    self.calendar = [NSCalendar currentCalendar];
    NSRange range = [self.calendar rangeOfUnit:NSCalendarUnitDay
                                        inUnit:NSCalendarUnitMonth
                                       forDate:[self monthDate]];
    return range.length;
}

//根據(jù)當(dāng)前年月返回日期
-(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;
    
}

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

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

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

@end

2募狂、創(chuàng)建一個(gè)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;

//時(shí)間回調(diào)
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 - 創(chuàng)建布局
-(void)createUI{
    
    height = [UIScreen mainScreen].bounds.size.height;
    width = [UIScreen mainScreen].bounds.size.width;
    
    //取消手勢(shì)
    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);
    }
    
}

//顯示手勢(shì)
-(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];
    }];
    
}

//取消手勢(shì)
-(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、創(chuàng)建一個(gè)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欣尼、全劇終

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市停蕉,隨后出現(xiàn)的幾起案子愕鼓,更是在濱河造成了極大的恐慌,老刑警劉巖慧起,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件菇晃,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡蚓挤,警方通過(guò)查閱死者的電腦和手機(jī)磺送,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門驻子,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人估灿,你說(shuō)我怎么就攤上這事崇呵。” “怎么了馅袁?”我有些...
    開(kāi)封第一講書人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵域慷,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我汗销,道長(zhǎng)犹褒,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任弛针,我火速辦了婚禮叠骑,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘削茁。我一直安慰自己座云,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布付材。 她就那樣靜靜地躺著,像睡著了一般圃阳。 火紅的嫁衣襯著肌膚如雪厌衔。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,462評(píng)論 1 302
  • 那天捍岳,我揣著相機(jī)與錄音富寿,去河邊找鬼。 笑死锣夹,一個(gè)胖子當(dāng)著我的面吹牛页徐,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播银萍,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼变勇,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了贴唇?” 一聲冷哼從身側(cè)響起搀绣,我...
    開(kāi)封第一講書人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎戳气,沒(méi)想到半個(gè)月后链患,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡瓶您,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年麻捻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了纲仍。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡贸毕,死狀恐怖郑叠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情崖咨,我是刑警寧澤锻拘,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站击蹲,受9級(jí)特大地震影響署拟,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜歌豺,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一推穷、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧类咧,春花似錦馒铃、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至值戳,卻和暖如春议谷,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背堕虹。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工卧晓, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人赴捞。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓逼裆,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親赦政。 傳聞我的和親對(duì)象是個(gè)殘疾皇子胜宇,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,101評(píng)論 1 32
  • 廢話不多說(shuō),直接上干貨 ---------------------------------------------...
    小小趙紙農(nóng)閱讀 3,357評(píng)論 0 15
  • 原文: iOS應(yīng)用架構(gòu)談 view層的組織和調(diào)用方案 iOS應(yīng)用架構(gòu)談 開(kāi)篇 iOS應(yīng)用架構(gòu)談 網(wǎng)絡(luò)層設(shè)計(jì)方案 i...
    難卻卻閱讀 1,262評(píng)論 0 7
  • 又是晚上我的手里拽著大半個(gè)月亮你在人間推開(kāi)了窗 一顆凡心在動(dòng)你在遙遠(yuǎn)的黑夜里長(zhǎng)嘆:天若有情昼钻,月如無(wú)恨 一片光脫了韁...
    2020號(hào)閱讀 373評(píng)論 29 22
  • 第二章 我還記得掸屡,在機(jī)場(chǎng)過(guò)夜的時(shí)候發(fā)生了很多奇怪的事情,為什么奇怪呢然评,從何說(shuō)起呢仅财?當(dāng)然是要從我10號(hào)晚上到上海機(jī)場(chǎng)...
    光芒萬(wàn)丈_閱讀 248評(píng)論 0 0