在開發(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地址古话,希望可以對您有所幫助雏吭!