时间选择器

在开发中,我们总会遇到一些需求,需要实现显示从今天到后面连续n(本例中n=4)天的时间选择。那么该如何实现这样的需求呢?

前段时间我们的项目中就遇到过这样的需求,当时我还是花了一些功夫的。由最初的初版到现在的版本,也是经历过不断的修改和完善,希望能够在您的项目开发中,对你有所帮助!

功能效果如下图:


时间选择器加载页面
提示用户选择时间页面
选择时间按钮状态页面

主要数据的代码实现

1、获取从今天开始后四天的日期

/// 用于存放月份和日的数组
- (NSMutableArray *)monthAndDayArray {
    if (!_monthAndDayArray) {
        _monthAndDayArray = [[NSMutableArray alloc] init];
        
        NSTimeInterval oneDay = 24 * 60 * 60;  // 一天一共有多少秒
        NSInteger showDays = 4;    // 需要显示的总天数
        
        // 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 = @"今天";
            }
            
            // 添加最终处理好的数据,将他们作为模型封装到数组中
            [_monthAndDayArray addObject:timeModel];
            
        }
        
    }
    return _monthAndDayArray;
}

2、将当前时间(NSDate)转化成年月日

#pragma mark-  将当前时间(NSDate)转化成年月日

/// 将当前时间(NSDate)转化成年月日
- (NSString *)getCurrentDateStringWithFormatter:(NSString *)formatter withCurrentDate:(NSDate *)currentDate {
    
    // 实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        // 设定时间格式,这里可以设置成自己需要的格式
    //    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // @"yyyy/MM/dd"
        [dateFormatter setDateFormat:formatter];
        
        // 设置时区
        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
        [dateFormatter setTimeZone:timeZone];
        
        NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    
    return currentDateString;
}

时间数据的创建

当然,这里的数据可以根据您项目的需求,进行网络请求实现这个数据的创建和加载。本例中就进行简单的数据创建和加载了。

- (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;
}

根据年月日计算对应日期的星期

- (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;
    }
}

时间的创建和实现

这里采用的是用一个UIView加载很多个按钮的实现方式,根据您的项目需求,你也可以采用UICollectionView的形式实现时间的加载和显示。

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);
}

/// 更新时间按钮的状态
- (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实现月份和日期

- (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;
}

弹窗的加载和实现

- (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的实现,如果您的项目中加载不了这个弹窗,那么你可以将mainWindow的创建由windows[0]改完keyWindow,如下所示:

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

UIWindow *mainWindow = [UIApplication sharedApplication].keyWindow;

尺寸大小可以根据您的屏幕和需求进行调整,本例中的代码采用的是1024*768的尺寸进行开发的。

最后附上Demo地址,希望可以对您有所帮助!

你可能感兴趣的:(时间选择器)