時間選擇器

在開發(fā)中凑术,我們總會遇到一些需求骄呼,需要實現(xiàn)顯示從今天到后面連續(xù)n(本例中n=4)天的時間選擇浪汪。那么該如何實現(xiàn)這樣的需求呢惰拱?

前段時間我們的項目中就遇到過這樣的需求雌贱,當時我還是花了一些功夫的。由最初的初版到現(xiàn)在的版本偿短,也是經(jīng)歷過不斷的修改和完善欣孤,希望能夠在您的項目開發(fā)中,對你有所幫助昔逗!

功能效果如下圖:


時間選擇器加載頁面
提示用戶選擇時間頁面
選擇時間按鈕狀態(tài)頁面

主要數(shù)據(jù)的代碼實現(xiàn)

1降传、獲取從今天開始后四天的日期

/// 用于存放月份和日的數(shù)組
- (NSMutableArray *)monthAndDayArray {
    if (!_monthAndDayArray) {
        _monthAndDayArray = [[NSMutableArray alloc] init];
        
        NSTimeInterval oneDay = 24 * 60 * 60;  // 一天一共有多少秒
        NSInteger showDays = 4;    // 需要顯示的總天數(shù)
        
        // 1.獲取當前日期
        NSDate *currentDate = [NSDate date];
        
        for (NSInteger i = 0; i < showDays; i++) {
            
            NSDate *appointDate = [currentDate initWithTimeIntervalSinceNow: oneDay * i];
            
            NSString *currentDate = [self getCurrentDateStringWithFormatter:@"yyyy-MM-dd" withCurrentDate:appointDate];
            
            NSInteger year = [[currentDate substringToIndex:4] integerValue];
            NSInteger month = [[currentDate substringWithRange:NSMakeRange(5, 2)] integerValue];
            NSInteger day = [[currentDate substringFromIndex:8] integerValue];
            
            NSString *mandd = [NSString stringWithFormat:@"%ld月%ld日", (long)month, (long)day];
            
            ASTimeModel *timeModel = [[ASTimeModel alloc] init];
            timeModel.monthAndDay = mandd;
            timeModel.year = year;
            timeModel.month = month;
            timeModel.day = day;
            timeModel.yearMonthDay = [NSString stringWithFormat:@"%ld年%@", (long)year, mandd];
            
            if (i == 0) {
                timeModel.weekday = @"今天";
            }
            
            // 添加最終處理好的數(shù)據(jù),將他們作為模型封裝到數(shù)組中
            [_monthAndDayArray addObject:timeModel];
            
        }
        
    }
    return _monthAndDayArray;
}

2纤子、將當前時間(NSDate)轉(zhuǎn)化成年月日

#pragma mark-  將當前時間(NSDate)轉(zhuǎn)化成年月日

/// 將當前時間(NSDate)轉(zhuǎn)化成年月日
- (NSString *)getCurrentDateStringWithFormatter:(NSString *)formatter withCurrentDate:(NSDate *)currentDate {
    
    // 實例化一個NSDateFormatter對象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        // 設(shè)定時間格式,這里可以設(shè)置成自己需要的格式
    //    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // @"yyyy/MM/dd"
        [dateFormatter setDateFormat:formatter];
        
        // 設(shè)置時區(qū)
        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
        [dateFormatter setTimeZone:timeZone];
        
        NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    
    return currentDateString;
}

時間數(shù)據(jù)的創(chuàng)建

當然搬瑰,這里的數(shù)據(jù)可以根據(jù)您項目的需求,進行網(wǎng)絡(luò)請求實現(xiàn)這個數(shù)據(jù)的創(chuàng)建和加載控硼。本例中就進行簡單的數(shù)據(jù)創(chuàng)建和加載了泽论。

- (NSArray *)timeArray {
    if (!_timeArray) {
        _timeArray = @[@"09:00", @"09:30", @"10:00", @"10:30", @"11:00", @"11:30", @"12:00", @"12:30", @"13:00", @"13:30", @"14:00", @"14:30", @"15:00", @"15:30", @"16:00", @"16:30", @"17:00", @"17:30", @"18:00", @"18:30", @"19:00", @"19:30", @"20:00", @"20:30", @"21:00"];
    }
    return _timeArray;
}

根據(jù)年月日計算對應(yīng)日期的星期

- (void)caculateWeekDayWithYear:(NSInteger) year month:(NSInteger)month day:(NSInteger)day {
    
    if(month == 1 || month == 2) {
        month += 12;
        year--;
    }
    
    NSInteger iWeek = (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400) % 7;
    
    switch (iWeek) {
        case 0:
            NSLog(@"星期一");
            self.weekday = @"周一";
            break;
            
        case 1:
            NSLog(@"星期二");
            self.weekday = @"周二";
            break;
            
        case 2:
            NSLog(@"星期三");
            self.weekday = @"周三";
            break;
            
        case 3:
            NSLog(@"星期四");
            self.weekday = @"周四";
            break;
            
        case 4:
            NSLog(@"星期五");
            self.weekday = @"周五";
            break;
            
        case 5:
            NSLog(@"星期六");
            self.weekday = @"周六";
            break;
            
        case 6:
            NSLog(@"星期日");
            self.weekday = @"周日";
            break;
            
            
        default:
            break;
    }
}

時間的創(chuàng)建和實現(xiàn)

這里采用的是用一個UIView加載很多個按鈕的實現(xiàn)方式,根據(jù)您的項目需求卡乾,你也可以采用UICollectionView的形式實現(xiàn)時間的加載和顯示翼悴。

CGFloat btnW = 84;
    CGFloat btnH = 30;
    NSInteger col = 4;
    CGFloat marginW = 50;
    CGFloat marginH = 10;
    
    for (NSInteger i = 0; i < self.timeArray.count; i++) {
        
        CGFloat btnX = i % col * (btnW + marginW);
        CGFloat btnY = i / col * (btnH + marginH);
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        btn.tag = i + 100;
        
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = 15;
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
        
        NSString *hour = [self.timeArray[i] componentsSeparatedByString:@":"].firstObject;
        NSString *minute = [self.timeArray[i] componentsSeparatedByString:@":"].lastObject;
        if ((self.hour > [hour integerValue]) || (self.hour == [hour integerValue] && self.minute >= [minute integerValue])) {
            
            btn.enabled = NO;
            [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        } else {
            
            btn.enabled = YES;
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        
        if (((self.day > self.currentDay) && (self.month == self.currentMonth)) || (self.month > self.currentMonth)) {
            
            btn.enabled = YES;
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        
        [btn setTitle:self.timeArray[i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(selecedCurrentBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.bottomBGView addSubview:btn];
    }
#pragma mark- function

- (void)selecedCurrentBtn:(UIButton *)sender {
    
    [self refreshTimeButton];
    
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        
        sender.backgroundColor = [UIColor blueColor];
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    }
    
    NSString *timeString = self.timeArray[sender.tag - 100];
    self.timeString = timeString;
    
    NSLog(@"timeString:%@", timeString);
}

/// 更新時間按鈕的狀態(tài)
- (void)refreshTimeButton {
    
    for (NSInteger i = 0; i < self.timeArray.count; i++) {
        UIButton *btn = [self.bottomBGView viewWithTag:i + 100];
        btn.selected = NO;
        btn.backgroundColor = [UIColor clearColor];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        NSString *hour = [self.timeArray[i] componentsSeparatedByString:@":"].firstObject;
        NSString *minute = [self.timeArray[i] componentsSeparatedByString:@":"].lastObject;
        if ((self.hour > [hour integerValue]) || (self.hour == [hour integerValue] && self.minute >= [minute integerValue])) {
            
            btn.enabled = NO;
            [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        } else {
            
            btn.enabled = YES;
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        
        if (((self.day > self.currentDay) && (self.month == self.currentMonth)) || (self.month > self.currentMonth)) {
            
            btn.enabled = YES;
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
}

UICollectionView實現(xiàn)月份和日期

- (UICollectionView *)monthAndDayCollectionView {
    if (!_monthAndDayCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 20;
        _monthAndDayCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _monthAndDayCollectionView.delegate = self;
        _monthAndDayCollectionView.dataSource = self;
        _monthAndDayCollectionView.bounces = YES;
        _monthAndDayCollectionView.showsVerticalScrollIndicator = NO;
        _monthAndDayCollectionView.showsHorizontalScrollIndicator = NO;
        _monthAndDayCollectionView.userInteractionEnabled = YES;
        _monthAndDayCollectionView.backgroundColor = [UIColor clearColor];
        
        // 默認選中第一個元素
        [_monthAndDayCollectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];

        
        [_monthAndDayCollectionView registerClass:[ASMonthAndDayCollectionViewCell class] forCellWithReuseIdentifier:[ASMonthAndDayCollectionViewCell cellIdentifier]];
//        [_monthAndDayCollectionView registerNib:[UINib nibWithNibName:[ASMonthAndDayCollectionViewCell cellIdentifier] bundle:nil] forCellWithReuseIdentifier:[ASMonthAndDayCollectionViewCell cellIdentifier]];
    }
    return _monthAndDayCollectionView;
}

彈窗的加載和實現(xiàn)

- (instancetype)showTimeSelectorPopoView {
    
    if (self == [super init]) {
        
        // 獲取當前時間
        [self getCurrentDate];
        
        [self setupUI];
    }
    return self;
}

+ (instancetype)showTimeSelectorPopoViewWithSelectedTimeOperation:(void(^)(NSString *selectedTime))selectedTimeOperation {
    
    if (_timeSelectorPopoViewManager == nil) {
        
        _timeSelectorPopoViewManager = [[self alloc] showTimeSelectorPopoView];
        _timeSelectorPopoViewManager.frame = [UIScreen mainScreen].bounds;
        _timeSelectorPopoViewManager.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        _timeSelectorPopoViewManager.selectedTimeOperation = selectedTimeOperation;
        
        UIWindow *mainWindow = [UIApplication sharedApplication].windows[0];
        [mainWindow addSubview:_timeSelectorPopoViewManager];
    }
    return _timeSelectorPopoViewManager;
}

此處mainWindow的實現(xiàn),如果您的項目中加載不了這個彈窗,那么你可以將mainWindow的創(chuàng)建由windows[0]改完keyWindow鹦赎,如下所示:

// UIWindow *mainWindow = [UIApplication sharedApplication].windows[0];

UIWindow *mainWindow = [UIApplication sharedApplication].keyWindow;

尺寸大小可以根據(jù)您的屏幕和需求進行調(diào)整谍椅,本例中的代碼采用的是1024*768的尺寸進行開發(fā)的。

最后附上Demo地址古话,希望可以對您有所幫助雏吭!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市陪踩,隨后出現(xiàn)的幾起案子杖们,更是在濱河造成了極大的恐慌,老刑警劉巖肩狂,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件摘完,死亡現(xiàn)場離奇詭異,居然都是意外死亡傻谁,警方通過查閱死者的電腦和手機孝治,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來审磁,“玉大人谈飒,你說我怎么就攤上這事√伲” “怎么了步绸?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長吃媒。 經(jīng)常有香客問我,道長吕喘,這世上最難降的妖魔是什么赘那? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮氯质,結(jié)果婚禮上募舟,老公的妹妹穿的比我還像新娘。我一直安慰自己闻察,他們只是感情好拱礁,可當我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著辕漂,像睡著了一般呢灶。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上钉嘹,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天鸯乃,我揣著相機與錄音,去河邊找鬼跋涣。 笑死缨睡,一個胖子當著我的面吹牛鸟悴,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播奖年,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼细诸,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了陋守?” 一聲冷哼從身側(cè)響起震贵,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎嗅义,沒想到半個月后屏歹,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡之碗,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年蝙眶,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片褪那。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡幽纷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出博敬,到底是詐尸還是另有隱情友浸,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布偏窝,位于F島的核電站收恢,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏祭往。R本人自食惡果不足惜伦意,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望硼补。 院中可真熱鬧驮肉,春花似錦、人聲如沸已骇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽褪储。三九已至卵渴,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間鲤竹,已是汗流浹背奖恰。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人瑟啃。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓论泛,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蛹屿。 傳聞我的和親對象是個殘疾皇子屁奏,可洞房花燭夜當晚...
    茶點故事閱讀 45,515評論 2 359

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