iOS 使用UIPickerView三級聯(lián)動實現(xiàn)選擇日期年月日

選擇時間

代碼里面有些自定義的宏,如果想要這個效果的朋友,不妨花幾分鐘把里面的宏改下等不報錯了,直接用這下面的代碼調(diào)用就可以了!

調(diào)用代碼

 SelectTimeV *selectTimeV = [[SelectTimeV alloc] init];
        
        selectTimeV.block = ^(NSString *timeStr) {
            
            if (timeStr) {
                
                [endTimeLabelV setRightLabelText:timeStr];
            }
            
        };
        [[UIApplication sharedApplication].keyWindow addSubview:selectTimeV];

.h文件

#import <UIKit/UIKit.h>

@interface SelectTimeV : UIView

@property (nonatomic, copy) void (^block)(NSString *);

@end

.m文件

#import "SelectTimeV.h"

@interface SelectTimeV ()<UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate>

{
    NSInteger yearIndex;
    
    NSInteger monthIndex;
    
    NSInteger dayIndex;
    
    UIView *topV;
}
@property (nonatomic, strong) UIPickerView *pickerView;

@property (nonatomic, strong) NSMutableArray *yearArray;

@property (nonatomic, strong) NSMutableArray *monthArray;

@property (nonatomic, strong) NSMutableArray *dayArray;



@end


@implementation SelectTimeV

- (NSMutableArray *)yearArray {
    
    if (_yearArray == nil) {
        
        _yearArray = [NSMutableArray array];
        
        for (int year = 2000; year < 2050; year++) {
            
            NSString *str = [NSString stringWithFormat:@"%d年", year];
            
            [_yearArray addObject:str];
        }
    }
    
    return _yearArray;
}

- (NSMutableArray *)monthArray {
    
    if (_monthArray == nil) {
        
        _monthArray = [NSMutableArray array];
        
        for (int month = 1; month <= 12; month++) {
            
            NSString *str = [NSString stringWithFormat:@"%02d月", month];
            
            [_monthArray addObject:str];
        }
    }
    
    return _monthArray;
}

- (NSMutableArray *)dayArray {
    
    if (_dayArray == nil) {
        
        _dayArray = [NSMutableArray array];
        
        for (int day = 1; day <= 31; day++) {
            
            NSString *str = [NSString stringWithFormat:@"%02d日", day];
            
            [_dayArray addObject:str];
        }
    }
    
    return _dayArray;
}


- (instancetype)init
{
    self = [super initWithFrame:[UIApplication sharedApplication].keyWindow.frame];
    if (self) {
        
        self.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.3];
        
        
        topV = [[UIView alloc] initWithFrame:CGRectMake(0, screenHeight, screenWidth, aspectRatio(40))];
        topV.backgroundColor = RGBACOLOR(242, 242, 242, 1.0);
        [self addSubview:topV];
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.frame = CGRectMake(0, 0, aspectRatio(100), aspectRatio(40));
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:blackFontColor forState:UIControlStateNormal];
        [cancelBtn.titleLabel setFont:regularFontWithSize(16)];
        [topV addSubview:cancelBtn];
        
        UIButton *yesBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        yesBtn.frame = CGRectMake(screenWidth - aspectRatio(100), 0, aspectRatio(100), aspectRatio(40));
        [yesBtn setTitle:@"完成" forState:UIControlStateNormal];
        [yesBtn setTitleColor:naviBarColor forState:UIControlStateNormal];
        [yesBtn.titleLabel setFont:regularFontWithSize(16)];
        [topV addSubview:yesBtn];
        
        [cancelBtn click:^(UIView *view) {
            
            if (_block) {
                _block(nil);
            }
            
            [self remove];
        }];
        
        [yesBtn click:^(UIView *view) {
            
            if (_block) {
                
                NSString *timeStr = [NSString stringWithFormat:@"%@%@%@",((UILabel *)[_pickerView viewForRow:yearIndex forComponent:0]).text, ((UILabel *)[_pickerView viewForRow:monthIndex forComponent:1]).text, ((UILabel *)[_pickerView viewForRow:dayIndex forComponent:2]).text];
                
               
                timeStr = [timeStr stringByReplacingOccurrencesOfString:@"年" withString:@"/"];
               
                timeStr = [timeStr stringByReplacingOccurrencesOfString:@"月" withString:@"/"];
               
                timeStr = [timeStr stringByReplacingOccurrencesOfString:@"日" withString:@""];
                
                _block(timeStr);
                
            }
            [self remove];
        }];
        
        [self click:^(UIView *view) {
            
            if (_block) {
                _block(nil);
            }
            [self remove];
        }];
        
    
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, topV.bottom, screenWidth, aspectRatio(207))];
        _pickerView.dataSource = self;
        _pickerView.delegate = self;
        _pickerView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_pickerView];
        
        NSCalendar *calendar = [[NSCalendar alloc]
                                initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        // 定義一個時間字段的旗標,指定將會獲取指定年软免、月舅踪、日、時肮韧、分、秒的信息
        unsigned unitFlags = NSCalendarUnitYear |
        NSCalendarUnitMonth |  NSCalendarUnitDay |
        NSCalendarUnitHour |  NSCalendarUnitMinute |
        NSCalendarUnitSecond | NSCalendarUnitWeekday;
        // 獲取不同時間字段的信息
        NSDateComponents *comp = [calendar components: unitFlags fromDate:[NSDate date]];
       
        yearIndex = [self.yearArray indexOfObject:[NSString stringWithFormat:@"%ld年", comp.year]];
        monthIndex = [self.monthArray indexOfObject:[NSString stringWithFormat:@"%02ld月", comp.month]];
        dayIndex = [self.dayArray indexOfObject:[NSString stringWithFormat:@"%02ld日", comp.day]];
        
        [_pickerView selectRow:yearIndex inComponent:0 animated:YES];
        [_pickerView selectRow:monthIndex inComponent:1 animated:YES];
        [_pickerView selectRow:dayIndex inComponent:2 animated:YES];

        [self pickerView:_pickerView didSelectRow:yearIndex inComponent:0];
        [self pickerView:_pickerView didSelectRow:monthIndex inComponent:1];
        [self pickerView:_pickerView didSelectRow:dayIndex inComponent:2];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            UILabel *label = (UILabel *)[_pickerView viewForRow:yearIndex forComponent:0];
            label.textColor = RGBACOLOR(26, 174, 135, 1.0);
            label.font = regularFontWithSize(16);
            
            label = (UILabel *)[_pickerView viewForRow:monthIndex forComponent:1];
            label.textColor = RGBACOLOR(26, 174, 135, 1.0);
            label.font = regularFontWithSize(16);
            
            label = (UILabel *)[_pickerView viewForRow:dayIndex forComponent:2];
            label.textColor = RGBACOLOR(26, 174, 135, 1.0);
            label.font = regularFontWithSize(16);
            
        });
        
        [UIView animateWithDuration:0.25 animations:^{
           
            topV.frame = CGRectMake(0, screenHeight - aspectRatio(247), screenWidth, aspectRatio(40));
            _pickerView.frame = CGRectMake(0, topV.bottom, screenWidth, aspectRatio(207));
        }];
        
    }
    return self;
}

#pragma mark -UIPickerView
#pragma mark UIPickerView的數(shù)據(jù)源
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return self.yearArray.count;
        
    }else if(component == 1) {
        
        return self.monthArray.count;
        
    }else {
        
        switch (monthIndex + 1) {
            
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12: return 31;
                
            case 4:
            case 6:
            case 9:
            case 11: return 30;
                
            default: return 28;
        }
    }
}


- (void)remove {
    
    [UIView animateWithDuration:0.25 animations:^{
        
        topV.frame = CGRectMake(0, screenHeight, screenWidth, aspectRatio(40));
        _pickerView.frame = CGRectMake(0, topV.bottom, screenWidth, aspectRatio(207));

    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
    }];

}
#pragma mark -UIPickerView的代理

// 滾動UIPickerView就會調(diào)用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) { 
        
        yearIndex = row;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            UILabel *label = (UILabel *)[pickerView viewForRow:row forComponent:component];
            label.textColor = RGBACOLOR(26, 174, 135, 1.0);
            label.font = regularFontWithSize(16);
            
        });
        
    }else if (component == 1) {
        
        monthIndex = row;
        
        [pickerView reloadComponent:2];
        
       
        if (monthIndex + 1 == 4 || monthIndex + 1 == 6 || monthIndex + 1 == 9 || monthIndex + 1 == 11) {
            
            if (dayIndex + 1 == 31) {
                
                dayIndex--;
            }
        }else if (monthIndex + 1 == 2) {
            
            if (dayIndex + 1 > 28) {
                dayIndex = 27;
            }
        }
        [pickerView selectRow:dayIndex inComponent:2 animated:YES];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            UILabel *label = (UILabel *)[pickerView viewForRow:row forComponent:component];
            label.textColor = RGBACOLOR(26, 174, 135, 1.0);
            label.font = regularFontWithSize(16);
            
            label = (UILabel *)[pickerView viewForRow:dayIndex forComponent:2];
            label.textColor = RGBACOLOR(26, 174, 135, 1.0);
            label.font = regularFontWithSize(16);
            
        });
    }else {
        
           dayIndex = row;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            UILabel *label = (UILabel *)[pickerView viewForRow:row forComponent:component];
            label.textColor = RGBACOLOR(26, 174, 135, 1.0);
            label.font = regularFontWithSize(16);
            
        });
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    //    //設(shè)置分割線的顏色
    //    for(UIView *singleLine in pickerView.subviews)
    //    {
    //        if (singleLine.frame.size.height < 1)
    //        {
    //            singleLine.backgroundColor = kSingleLineColor;
    //        }
    //    }
    
    //設(shè)置文字的屬性
    UILabel *genderLabel = [[UILabel alloc] init];
    genderLabel.textAlignment = NSTextAlignmentCenter;
    genderLabel.textColor = RGBACOLOR(153, 153, 153, 1.0);
    genderLabel.font = regularFontWithSize(14);
    if (component == 0) {
        
        genderLabel.text = self.yearArray[row];
        
    }else if (component == 1) {
        
        genderLabel.text = self.monthArray[row];
        
    }else {
        
        genderLabel.text = self.dayArray[row];
    }
    
    return genderLabel;
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末旺订,一起剝皮案震驚了整個濱河市弄企,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌区拳,老刑警劉巖拘领,帶你破解...
    沈念sama閱讀 206,482評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異樱调,居然都是意外死亡约素,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,377評論 2 382
  • 文/潘曉璐 我一進店門笆凌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來圣猎,“玉大人,你說我怎么就攤上這事乞而∷突冢” “怎么了?”我有些...
    開封第一講書人閱讀 152,762評論 0 342
  • 文/不壞的土叔 我叫張陵爪模,是天一觀的道長欠啤。 經(jīng)常有香客問我,道長屋灌,這世上最難降的妖魔是什么洁段? 我笑而不...
    開封第一講書人閱讀 55,273評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮共郭,結(jié)果婚禮上祠丝,老公的妹妹穿的比我還像新娘疾呻。我一直安慰自己,他們只是感情好纽疟,可當我...
    茶點故事閱讀 64,289評論 5 373
  • 文/花漫 我一把揭開白布罐韩。 她就那樣靜靜地躺著,像睡著了一般污朽。 火紅的嫁衣襯著肌膚如雪散吵。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,046評論 1 285
  • 那天蟆肆,我揣著相機與錄音矾睦,去河邊找鬼。 笑死炎功,一個胖子當著我的面吹牛枚冗,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蛇损,決...
    沈念sama閱讀 38,351評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼赁温,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了淤齐?” 一聲冷哼從身側(cè)響起股囊,我...
    開封第一講書人閱讀 36,988評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎更啄,沒想到半個月后稚疹,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,476評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡祭务,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,948評論 2 324
  • 正文 我和宋清朗相戀三年内狗,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片义锥。...
    茶點故事閱讀 38,064評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡柳沙,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出拌倍,到底是詐尸還是另有隱情赂鲤,我是刑警寧澤,帶...
    沈念sama閱讀 33,712評論 4 323
  • 正文 年R本政府宣布贰拿,位于F島的核電站,受9級特大地震影響熄云,放射性物質(zhì)發(fā)生泄漏膨更。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,261評論 3 307
  • 文/蒙蒙 一缴允、第九天 我趴在偏房一處隱蔽的房頂上張望荚守。 院中可真熱鬧珍德,春花似錦、人聲如沸矗漾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,264評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽敞贡。三九已至泵琳,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間誊役,已是汗流浹背获列。 一陣腳步聲響...
    開封第一講書人閱讀 31,486評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蛔垢,地道東北人击孩。 一個月前我還...
    沈念sama閱讀 45,511評論 2 354
  • 正文 我出身青樓,卻偏偏與公主長得像鹏漆,于是被迫代替她去往敵國和親巩梢。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,802評論 2 345

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

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 171,510評論 25 707
  • 1艺玲,NSObject中description屬性的意義括蝠,它可以重寫嗎?答案:每當 NSLog(@"")函數(shù)中出現(xiàn) ...
    eightzg閱讀 4,132評論 2 19
  • 文/莔莔有神 最近最大的一個感受是又跛,并不是捧著一本書從頭翻到尾就叫讀書。 一來是不管是朋友圈還是現(xiàn)實生活中若治,總有人...
    萌萌有神閱讀 3,171評論 3 26
  • 佩戴的手環(huán)里自己設(shè)了一個5點30的鬧鈴慨蓝,用于提醒到點可以起來做艾灸養(yǎng)生,但并沒有要求自己非午起來端幼,得取決于...
    萬萬萬主播閱讀 215評論 0 0
  • 當你盯著電腦時礼烈,阿拉斯加的鱈魚正躍出水面; 當你愁眉發(fā)呆時婆跑,梅里雪山的金絲猴剛好爬上樹尖此熬; 當你擠地鐵時,西藏的云...
    阿芝醬閱讀 54評論 0 0