KBDatePickerView.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. #import "KBDatePickerView.h"
  2. #define STACK_VIEW_HEIGHT 128
  3. DEFINE_ENUM(KBTableViewTag, TABLE_TAG)
  4. DEFINE_ENUM(KBDatePickerMode, PICKER_MODE)
  5. @implementation NSString (format)
  6. + (id)kb_stringWithFormat:(const char*) fmt,...{
  7. va_list args;
  8. char temp[2048];
  9. va_start(args, fmt);
  10. vsprintf(temp, fmt, args);
  11. va_end(args);
  12. return [[NSString alloc] initWithUTF8String:temp];
  13. }
  14. @end
  15. @interface UITableView (yep)
  16. - (NSIndexPath *)_focusedCellIndexPath;
  17. @end
  18. @implementation UIView (Helper)
  19. - (void)removeAllSubviews {
  20. [[self subviews] enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  21. [obj removeFromSuperview];
  22. }];
  23. }
  24. @end
  25. @implementation UIStackView (Helper)
  26. - (void)removeAllArrangedSubviews {
  27. [[self arrangedSubviews] enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  28. if ([obj respondsToSelector:@selector(removeAllArrangedSubviews)]){
  29. [obj removeAllArrangedSubviews];
  30. }
  31. [self removeArrangedSubview:obj];
  32. }];
  33. }
  34. - (void)setArrangedViews:(NSArray *)views {
  35. if ([self arrangedSubviews].count > 0){
  36. [self removeAllArrangedSubviews];
  37. }
  38. [views enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  39. [self addArrangedSubview:obj];
  40. }];
  41. }
  42. @end
  43. @interface KBTableView(){
  44. NSIndexPath *_selectedIndexPath;
  45. }
  46. @end
  47. @implementation KBTableView
  48. - (instancetype)initWithTag:(KBTableViewTag)tag delegate:(id)delegate {
  49. self = [super initWithFrame:CGRectZero style:UITableViewStylePlain];
  50. if (self){
  51. self.tag = tag;
  52. self.dataSource = delegate;
  53. self.delegate = delegate;
  54. }
  55. return self;
  56. }
  57. - (NSArray *)visibleValues {
  58. __block NSMutableArray *visibleValues = [NSMutableArray new];
  59. [self.visibleCells enumerateObjectsUsingBlock:^(__kindof UITableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  60. NSString *value = obj.textLabel.text;
  61. [visibleValues addObject:value];
  62. }];
  63. return visibleValues;;
  64. }
  65. - (NSIndexPath *)selectedIndexPath {
  66. return _selectedIndexPath;
  67. }
  68. - (id)valueForIndexPath:(NSIndexPath *)indexPath {
  69. return [self cellForRowAtIndexPath:indexPath].textLabel.text;
  70. }
  71. - (void)setSelectedIndexPath:(NSIndexPath *)selectedIndexPath {
  72. _selectedIndexPath = selectedIndexPath;
  73. id value = [self valueForIndexPath:selectedIndexPath];
  74. if (value){
  75. //DPLog(@"found cell in %lu", self.tag);
  76. _selectedValue = value;
  77. //DPLog(@"selected value set: %@ for index; %lu", _selectedValue, selectedIndexPath.row);
  78. }
  79. }
  80. @end
  81. @interface KBDatePickerView () {
  82. NSDate *_currentDate;
  83. NSDate *_minimumDate;
  84. NSDate *_maximumDate;
  85. NSArray *_tableViews;
  86. BOOL _pmSelected;
  87. NSMutableDictionary *_selectedRowData;
  88. KBDatePickerMode _datePickerMode;
  89. NSInteger _minYear;
  90. NSInteger _maxYear;
  91. NSInteger _yearSelected;
  92. NSInteger _monthSelected;
  93. NSInteger _daySelected;
  94. NSInteger _hourSelected;
  95. NSInteger _minuteSelected;
  96. NSInteger _currentMonthDayCount; //current months
  97. }
  98. @property (nonatomic, strong) NSArray *hourData;
  99. @property (nonatomic, strong) NSArray *minutesData;
  100. @property (nonatomic, strong) NSArray *dayData;
  101. @property UIStackView *datePickerStackView;
  102. @property KBTableView *monthTable;
  103. @property KBTableView *dayTable;
  104. @property KBTableView *yearTable;
  105. @property KBTableView *hourTable;
  106. @property KBTableView *minuteTable;
  107. @property KBTableView *amPMTable;
  108. @property UILabel *monthLabel;
  109. @property UILabel *dayLabel;
  110. @property UILabel *yearLabel;
  111. @property UILabel *datePickerLabel;
  112. @property NSLayoutConstraint *widthConstraint;
  113. @property UILabel *unsupportedLabel;
  114. @end
  115. @implementation KBDatePickerView
  116. - (void)menuGestureRecognized:(UITapGestureRecognizer *)gestureRecognizer {
  117. if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
  118. id superview = [self superview];
  119. if ([superview respondsToSelector:@selector(delegate)]){
  120. UIViewController *vc = [superview delegate];
  121. DPLog(@"delegateView: %@", vc);
  122. [vc setNeedsFocusUpdate];
  123. [vc updateFocusIfNeeded];
  124. }
  125. /*
  126. //[self setPreferredFocusedItem:self.toggleTypeButton]; //PRIVATE_API call, trying to avoid those to stay app store friendly!
  127. UIApplication *sharedApp = [UIApplication sharedApplication];
  128. #pragma clang diagnostic push
  129. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  130. UIWindow *window = [sharedApp keyWindow];
  131. #pragma clang diagnostic pop
  132. UIViewController *rootViewController = [window rootViewController];
  133. if (rootViewController.view == self.superview){
  134. [rootViewController setNeedsFocusUpdate];
  135. [rootViewController updateFocusIfNeeded];
  136. } */
  137. }
  138. }
  139. + (NSDateFormatter *)sharedDateFormatter {
  140. static dispatch_once_t onceToken;
  141. static NSDateFormatter *shared = nil;
  142. if(shared == nil) {
  143. dispatch_once(&onceToken, ^{
  144. shared = [[NSDateFormatter alloc] init];
  145. [shared setTimeZone:[NSTimeZone localTimeZone]];
  146. [shared setDateFormat:@"E, MMM d, yyyy h:mm a"];
  147. });
  148. }
  149. return shared;
  150. }
  151. - (NSDateComponents *)currentComponents:(NSCalendarUnit)unitFlags {
  152. return [[self calendar] components:unitFlags fromDate:self.date];
  153. }
  154. - (NSDate *)date {
  155. if (!_currentDate){
  156. [self setDate:[NSDate date]];
  157. }
  158. return _currentDate;
  159. }
  160. - (NSCalendar *)calendar {
  161. return [NSCalendar currentCalendar];
  162. }
  163. - (void)setDate:(NSDate *)date animated:(BOOL)animated {
  164. _currentDate = date;
  165. [self scrollToCurrentDateAnimated:animated];
  166. }
  167. - (void)setMinimumDate:(NSDate *)minimumDate {
  168. _minimumDate = minimumDate;
  169. [self populateYearsForDateRange];
  170. }
  171. - (NSDate *)minimumDate {
  172. return _minimumDate;
  173. }
  174. - (NSDate *)maximumDate {
  175. return _maximumDate;
  176. }
  177. - (void)setMaximumDate:(NSDate *)maximumDate {
  178. _maximumDate = maximumDate;
  179. [self populateYearsForDateRange];
  180. }
  181. - (void)setDate:(NSDate *)date {
  182. _currentDate = date;
  183. [self setDate:date animated:true];
  184. }
  185. - (BOOL)isEnabled {
  186. return FALSE;
  187. }
  188. - (id)init {
  189. self = [super init];
  190. _pmSelected = false;
  191. _showDateLabel = true;
  192. if (![self date]){
  193. [self setDate:[NSDate date]];
  194. }
  195. _topOffset = 80;
  196. UITapGestureRecognizer *menuTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuGestureRecognized:)];
  197. menuTap.numberOfTapsRequired = 1;
  198. menuTap.allowedPressTypes = @[@(UIPressTypeMenu)];
  199. [self addGestureRecognizer:menuTap];
  200. _selectedRowData = [NSMutableDictionary new];
  201. _datePickerMode = KBDatePickerModeDate;
  202. [self layoutViews];
  203. return self;
  204. }
  205. - (void)layoutForTime {
  206. if (self.hourTable){
  207. [self.hourTable removeFromSuperview];
  208. self.hourTable = nil;
  209. [self.minuteTable removeFromSuperview];
  210. self.minuteTable = nil;
  211. [self.amPMTable removeFromSuperview];
  212. self.amPMTable = nil;
  213. _tableViews = nil;
  214. }
  215. [self setupTimeData];
  216. self.hourTable = [[KBTableView alloc] initWithTag:KBTableViewTagHours delegate:self];
  217. self.minuteTable = [[KBTableView alloc] initWithTag:KBTableViewTagMinutes delegate:self];
  218. self.amPMTable = [[KBTableView alloc] initWithTag:KBTableViewTagAMPM delegate:self];
  219. self.amPMTable.contentInset = UIEdgeInsetsMake(0, 0, 40, 0);
  220. _tableViews = @[_hourTable, _minuteTable, _amPMTable];
  221. }
  222. - (void)layoutForDate {
  223. if (self.monthLabel){
  224. [self.monthLabel removeFromSuperview];
  225. self.monthLabel = nil;
  226. [self.yearLabel removeFromSuperview];
  227. self.yearLabel = nil;
  228. [self.dayLabel removeFromSuperview];
  229. self.dayLabel = nil;
  230. self.monthTable = nil;
  231. self.yearTable = nil;
  232. self.dayTable = nil;
  233. _tableViews = nil;
  234. }
  235. [self populateDaysForCurrentMonth];
  236. [self populateYearsForDateRange];
  237. self.monthLabel = [[UILabel alloc] init];
  238. self.monthLabel.translatesAutoresizingMaskIntoConstraints = false;
  239. self.monthLabel.text = @"Month";
  240. self.yearLabel = [[UILabel alloc] init];
  241. self.yearLabel.translatesAutoresizingMaskIntoConstraints = false;
  242. self.yearLabel.text = @"Year";
  243. self.dayLabel = [[UILabel alloc] init];
  244. self.dayLabel.translatesAutoresizingMaskIntoConstraints = false;
  245. self.dayLabel.text = @"Day";
  246. self.monthTable = [[KBTableView alloc] initWithTag:KBTableViewTagMonths delegate:self];
  247. self.yearTable = [[KBTableView alloc] initWithTag:KBTableViewTagYears delegate:self];
  248. self.dayTable = [[KBTableView alloc] initWithTag:KBTableViewTagDays delegate:self];
  249. _tableViews = @[_monthTable, _dayTable, _yearTable];
  250. [self addSubview:self.monthLabel];
  251. [self addSubview:self.yearLabel];
  252. [self addSubview:self.dayLabel];
  253. }
  254. - (void)layoutLabelsForDate {
  255. [self.monthLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:_topOffset].active = true;
  256. [self.dayLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:_topOffset].active = true;
  257. [self.dayLabel.centerXAnchor constraintEqualToAnchor:self.dayTable.centerXAnchor].active = true;
  258. [self.monthLabel.centerXAnchor constraintEqualToAnchor:self.monthTable.centerXAnchor].active = true;
  259. [self.yearLabel.centerXAnchor constraintEqualToAnchor:self.yearTable.centerXAnchor].active = true;
  260. [self.yearLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:_topOffset].active = true;
  261. [self.monthLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:_topOffset].active = true;
  262. }
  263. - (void)layoutUnsupportedView {
  264. if (_datePickerStackView != nil){
  265. [_datePickerStackView removeAllArrangedSubviews];
  266. [_datePickerStackView removeFromSuperview];
  267. _datePickerStackView = nil;
  268. }
  269. self.unsupportedLabel = [[UILabel alloc] init];
  270. [self addSubview:self.unsupportedLabel];
  271. self.unsupportedLabel.translatesAutoresizingMaskIntoConstraints = false;
  272. [self.unsupportedLabel.centerYAnchor constraintEqualToAnchor:self.centerYAnchor].active = true;
  273. [self.unsupportedLabel.centerXAnchor constraintEqualToAnchor:self.centerXAnchor].active = true;
  274. self.unsupportedLabel.text = [NSString kb_stringWithFormat:"Error: currently '%s' is an unsuppported configuration.", [NSStringFromKBDatePickerMode(self.datePickerMode) UTF8String]];
  275. }
  276. - (void)layoutForDateAndTime {
  277. [self layoutUnsupportedView];
  278. }
  279. - (void)layoutForCountdownTimer {
  280. [self layoutUnsupportedView];
  281. }
  282. - (void)layoutLabelsForTime {
  283. }
  284. - (void)setupLabelsForMode {
  285. switch (self.datePickerMode) {
  286. case KBDatePickerModeTime:
  287. [self layoutLabelsForTime];
  288. break;
  289. case KBDatePickerModeDate:
  290. [self layoutLabelsForDate];
  291. break;
  292. case KBDatePickerModeDateAndTime:
  293. [self layoutForDateAndTime];
  294. break;
  295. case KBDatePickerModeCountDownTimer:
  296. [self layoutForCountdownTimer];
  297. break;
  298. default:
  299. break;
  300. }
  301. }
  302. - (void)viewSetupForMode {
  303. if (self.unsupportedLabel){
  304. [self.unsupportedLabel removeFromSuperview];
  305. self.unsupportedLabel = nil;
  306. }
  307. switch (self.datePickerMode) {
  308. case KBDatePickerModeTime:
  309. [self layoutForTime];
  310. break;
  311. case KBDatePickerModeDate:
  312. [self layoutForDate];
  313. break;
  314. case KBDatePickerModeDateAndTime:
  315. [self layoutForDateAndTime];
  316. break;
  317. case KBDatePickerModeCountDownTimer:
  318. [self layoutForCountdownTimer];
  319. break;
  320. default:
  321. break;
  322. }
  323. }
  324. - (NSArray *)createNumberArray:(NSInteger)count zeroIndex:(BOOL)zeroIndex leadingZero:(BOOL)leadingZero {
  325. __block NSMutableArray *_newArray = [NSMutableArray new];
  326. int startIndex = 1;
  327. if (zeroIndex){
  328. startIndex = 0;
  329. }
  330. for (int i = startIndex; i < count+startIndex; i++){
  331. if (leadingZero){
  332. [_newArray addObject:[NSString kb_stringWithFormat:"%02i", i]];
  333. } else {
  334. [_newArray addObject:[NSString kb_stringWithFormat:"%i", i]];
  335. }
  336. }
  337. return _newArray;
  338. }
  339. - (NSArray *)monthData {
  340. return [[self calendar] monthSymbols];
  341. }
  342. - (void)scrollToCurrentDateAnimated:(BOOL)animated {
  343. if (self.datePickerMode == KBDatePickerModeTime){
  344. [self loadTimeFromDateAnimated:animated];
  345. } else {
  346. NSDateComponents *components = [self currentComponents:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay];
  347. NSInteger monthIndex = components.month-1;
  348. NSString *monthSymbol = self.monthData[monthIndex];
  349. if (![self.monthTable.selectedValue isEqualToString:monthSymbol]){
  350. [self scrollToValue:monthSymbol inTableViewType:KBTableViewTagMonths animated:animated];
  351. }
  352. NSInteger dayIndex = components.day;
  353. NSString *dayString = [NSString kb_stringWithFormat:"%i",dayIndex];
  354. if (![[_dayTable selectedValue] isEqualToString:dayString]){
  355. [self scrollToValue:dayString inTableViewType:KBTableViewTagDays animated:animated];
  356. }
  357. NSInteger yearIndex = components.year-1;
  358. //DPLog(@"year index: %lu", yearIndex);
  359. NSString *yearString = [NSString kb_stringWithFormat:"%i",yearIndex];
  360. //DPLog(@"year index: %@", yearString);
  361. if (![[_yearTable selectedValue] isEqualToString:yearString]){
  362. _yearSelected = yearIndex;
  363. [self scrollToValue:yearString inTableViewType:KBTableViewTagYears animated:animated];
  364. }
  365. [self delayedUpdateFocus];
  366. }
  367. }
  368. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  369. if (tableView == _monthTable){
  370. return [self infiniteNumberOfRowsInSection:section];
  371. } else if (tableView == _dayTable){
  372. return [self infiniteNumberOfRowsInSection:section];
  373. } else if (tableView == _hourTable){
  374. return [self infiniteNumberOfRowsInSection:section];
  375. } else if (tableView == _minuteTable){
  376. return [self infiniteNumberOfRowsInSection:section];
  377. } else if (tableView == _amPMTable){
  378. return 2;
  379. } else if (tableView == _yearTable){
  380. return _maxYear - _minYear;
  381. }
  382. return 0;
  383. }
  384. +(id)todayInYear:(NSInteger)year {
  385. NSDateComponents *dc = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitYear | NSCalendarUnitMonth fromDate:[NSDate date]];
  386. dc.year = year;
  387. return [[NSCalendar currentCalendar] dateFromComponents:dc];
  388. }
  389. - (void)updateDetailsIfContinuous:(NSIndexPath *)indexPath inTable:(KBTableView *)tableView {
  390. NSDateComponents *components = [self currentComponents:NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute];
  391. NSArray *dataSource = nil;
  392. NSInteger normalizedIndex = NSNotFound;
  393. if (tableView == _monthTable){
  394. dataSource = self.monthData;
  395. normalizedIndex = indexPath.row % dataSource.count;
  396. //DPLog(@"normalizedIndex: %lu s: %@", normalizedIndex, [dataSource objectAtIndex: normalizedIndex]);
  397. components.month = normalizedIndex + 1;
  398. _monthSelected = components.month;
  399. NSDate *newDate = [[self calendar] dateFromComponents:components];
  400. _currentDate = newDate; //set ivar so w dont set off any additional UI craziness.
  401. } else if (tableView == _dayTable){
  402. dataSource = self.dayData;
  403. normalizedIndex = indexPath.row % dataSource.count;
  404. //DPLog(@"_dayTable normalizedIndex: %lu s: %@", normalizedIndex, [dataSource objectAtIndex: normalizedIndex]);
  405. components.day = normalizedIndex + 1;
  406. _daySelected = components.day;
  407. NSDate *newDate = [[self calendar] dateFromComponents:components];
  408. _currentDate = newDate; //set ivar so w dont set off any additional UI craziness.
  409. } else if (tableView == _minuteTable){
  410. dataSource = self.minutesData;
  411. normalizedIndex = indexPath.row % dataSource.count;
  412. //DPLog(@"_minuteTable normalizedIndex: %lu s: %@", normalizedIndex, [dataSource objectAtIndex: normalizedIndex]);
  413. components.minute = normalizedIndex;
  414. _minuteSelected = components.minute;
  415. NSDate *newDate = [[self calendar] dateFromComponents:components];
  416. _currentDate = newDate; //set ivar so w dont set off any additional UI craziness.
  417. } else if (tableView == _hourTable){
  418. dataSource = self.hourData;
  419. normalizedIndex = indexPath.row % dataSource.count;
  420. //NSString *s = [dataSource objectAtIndex: normalizedIndex];
  421. if (_pmSelected){
  422. if (normalizedIndex != 11){
  423. normalizedIndex+=12;
  424. }
  425. } else {
  426. if (normalizedIndex == 11){
  427. normalizedIndex+=12;
  428. }
  429. }
  430. //DPLog(@"normalizedIndex: %lu s: %@", normalizedIndex, [dataSource objectAtIndex: normalizedIndex]);
  431. components.hour = normalizedIndex + 1;
  432. _hourSelected = components.hour;
  433. NSDate *newDate = [[self calendar] dateFromComponents:components];
  434. _currentDate = newDate; //set ivar so w dont set off any additional UI craziness.
  435. } else if (tableView == _yearTable){
  436. //NSInteger year = [[self calendar] component:NSCalendarUnitYear fromDate:self.date];
  437. NSInteger year = [_yearTable.selectedIndexPath row];
  438. NSInteger adjustment = 1;
  439. //DPLog(@"_minYear: %lu", _minYear);
  440. if (_minYear > 1){
  441. //DPLog(@"adjust the year, we dont start at 1!");
  442. adjustment = 0;
  443. year = [_yearTable.selectedValue integerValue];
  444. }
  445. //DPLog(@"year: %lu", year);
  446. components.year = year + adjustment;
  447. _yearSelected = components.year;
  448. NSDate *newDate = nil;
  449. do {
  450. newDate = [[self calendar] dateFromComponents:components];
  451. components.day -= 1;
  452. } while (newDate == nil || ([[self calendar] component:NSCalendarUnitMonth fromDate:newDate] != components.month));
  453. _currentDate = newDate;
  454. } else if (tableView == _amPMTable){
  455. BOOL previousState = _pmSelected;
  456. //DPLog(@"_hourSelected: %lu previousState: %d", _hourSelected, previousState);
  457. if (indexPath.row == 0){
  458. _pmSelected = false;
  459. if(_hourSelected != 0){
  460. if (previousState != _pmSelected){
  461. components.hour-=12;
  462. _hourSelected = components.hour;
  463. NSDate *date = [[self calendar] dateFromComponents:components];
  464. if (date){
  465. _currentDate = date;
  466. }
  467. }
  468. }
  469. } else if(indexPath.row == 1) {
  470. _pmSelected = true;
  471. if(_hourSelected != 0 && previousState != _pmSelected){
  472. components.hour+=12;
  473. _hourSelected = components.hour;
  474. NSDate *date = [[self calendar] dateFromComponents:components];
  475. if (date){
  476. _currentDate = date;
  477. }
  478. }
  479. }
  480. }
  481. [self selectionOccured];
  482. }
  483. - (void)selectMonthAtIndex:(NSInteger)index {
  484. NSDateComponents *comp = [self currentComponents:NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitYear];
  485. NSInteger adjustedIndex = index;
  486. if (index > self.monthData.count){
  487. adjustedIndex = index % self.monthData.count;
  488. }
  489. comp.month = adjustedIndex;
  490. [self setDate:[[self calendar] dateFromComponents:comp]];
  491. }
  492. - (BOOL)tableView:(UITableView *)tableView canFocusRowAtIndexPath:(NSIndexPath *)indexPath {
  493. if (tableView.tag == KBTableViewTagDays){
  494. NSInteger normalized = (indexPath.row % self.dayData.count) + 1;
  495. if (normalized > _currentMonthDayCount){
  496. return false;
  497. }
  498. }
  499. return true;
  500. }
  501. - (void)toggleMidnight {
  502. NSInteger index = 1;
  503. if (_pmSelected){
  504. index = 0;
  505. }
  506. [self.amPMTable selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:true scrollPosition:UITableViewScrollPositionTop];
  507. _pmSelected = !_pmSelected;
  508. }
  509. - (void)toggleMidnightIfNecessaryWithPrevious:(NSInteger)previousRow next:(NSInteger)nextRow {
  510. if (previousRow == 11 && nextRow == 12 && !_pmSelected){
  511. [self toggleMidnight];
  512. }
  513. if (previousRow == 12 && nextRow == 1 && !_pmSelected){
  514. [self toggleMidnight];
  515. }
  516. }
  517. - (BOOL)contextBrothers:(UITableViewFocusUpdateContext *)context {
  518. UIView *previousCell = context.previouslyFocusedView;
  519. UIView *newCell = context.nextFocusedView;
  520. return (previousCell.superview == newCell.superview);
  521. }
  522. - (void)tableView:(UITableView *)tableView didUpdateFocusInContext:(UITableViewFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator {
  523. [coordinator addCoordinatedAnimations:^{
  524. NSIndexPath *nextIndexPath = context.nextFocusedIndexPath;
  525. KBTableView *table = (KBTableView *)tableView;
  526. if ([self contextBrothers:context]){
  527. if (table.tag == KBTableViewTagHours){
  528. NSIndexPath *previous = context.previouslyFocusedIndexPath;
  529. NSInteger previousRow = (previous.row % self.hourData.count)+1;
  530. NSInteger nextRow = (nextIndexPath.row % self.hourData.count)+1;
  531. if ((previousRow == 11 && nextRow == 12) || (previousRow == 12 && nextRow == 11)){
  532. [self toggleMidnight];
  533. }
  534. }
  535. }
  536. if ([table respondsToSelector:@selector(setSelectedIndexPath:)]){
  537. if (nextIndexPath != nil){
  538. //DPLog(@"next ip: %lu table: %@", ip.row, NSStringFromKBTableViewTag((KBTableViewTag)tableView.tag));
  539. [table setSelectedIndexPath:nextIndexPath];
  540. [self updateDetailsIfContinuous:nextIndexPath inTable:table];
  541. if (tableView.tag == KBTableViewTagMonths){
  542. [self populateDaysForCurrentMonth];
  543. }
  544. }
  545. }
  546. [tableView selectRowAtIndexPath:nextIndexPath animated:false scrollPosition:UITableViewScrollPositionTop];
  547. } completion:^{
  548. }];
  549. }
  550. - (NSInteger)infiniteNumberOfRowsInSection:(NSInteger)section {
  551. return NUMBER_OF_CELLS;
  552. }
  553. - (void)populateYearsForDateRange {
  554. _minYear = self.minimumDate != nil ? [[self calendar] component:NSCalendarUnitYear fromDate:self.minimumDate] : 1;
  555. _maxYear = self.maximumDate != nil ? [[self calendar] component:NSCalendarUnitYear fromDate:self.maximumDate] : NUMBER_OF_CELLS;
  556. //DPLog(@"minYear: %lu", _minYear);
  557. //DPLog(@"maxYear: %lu", _maxYear);
  558. //DPLog(@"selectedValue: %@", _yearTable.selectedValue);
  559. //DPLog(@"currentYear: %lu", _yearSelected);
  560. if (!_yearTable.selectedValue && _yearSelected != 0){
  561. if (_minYear > 1){
  562. NSInteger yearDifference = _yearSelected - _minYear;
  563. //DPLog(@"year difference: %lu", yearDifference);
  564. [self.yearTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:yearDifference inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:false];
  565. }
  566. }
  567. [self.yearTable reloadData];
  568. }
  569. - (void)populateDaysForCurrentMonth {
  570. NSRange days = [[self calendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self.date];
  571. _currentMonthDayCount = days.length; //this is used to push a date back if they've gone too far.
  572. if (!self.dayData){ //only need to populate it once
  573. self.dayData = [self createNumberArray:31 zeroIndex:false leadingZero:false];
  574. [self.dayTable reloadData];
  575. }
  576. }
  577. - (void)setupTimeData {
  578. self.hourData = [self createNumberArray:12 zeroIndex:false leadingZero:false];
  579. self.minutesData = [self createNumberArray:60 zeroIndex:true leadingZero:true];
  580. }
  581. - (NSInteger)startIndexForHours {
  582. return 24996;
  583. }
  584. - (NSInteger)startIndexForMinutes {
  585. return 24000;
  586. }
  587. - (void)loadTimeFromDateAnimated:(BOOL)animated {
  588. NSDateComponents *components = [self currentComponents:NSCalendarUnitHour | NSCalendarUnitMinute];
  589. NSInteger hour = components.hour;
  590. NSInteger minutes = components.minute;
  591. BOOL isPM = (hour >= 12);
  592. if (isPM){
  593. _pmSelected = true;
  594. hour = hour-12;
  595. NSIndexPath *amPMIndex = [NSIndexPath indexPathForRow:1 inSection:0];
  596. [self.amPMTable scrollToRowAtIndexPath:amPMIndex atScrollPosition:UITableViewScrollPositionTop animated:false];
  597. }
  598. NSString *hourValue = [NSString kb_stringWithFormat:"%lu", hour];
  599. NSString *minuteValue = [NSString kb_stringWithFormat:"%lu", minutes];
  600. DPLog(@"hours %@ minutes %@", hourValue, minuteValue);
  601. if (![[self.hourTable selectedValue] isEqualToString:hourValue]){
  602. [self scrollToValue:hourValue inTableViewType:KBTableViewTagHours animated:animated];
  603. }
  604. if (![[self.minuteTable selectedValue] isEqualToString:minuteValue]){
  605. [self scrollToValue:minuteValue inTableViewType:KBTableViewTagMinutes animated:animated];
  606. }
  607. }
  608. - (void)delayedUpdateFocus {
  609. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  610. [self setNeedsFocusUpdate];
  611. [self updateFocusIfNeeded];
  612. });
  613. }
  614. - (void)scrollToValue:(id)value inTableViewType:(KBTableViewTag)type animated:(BOOL)animated {
  615. NSInteger foundIndex = NSNotFound;
  616. NSIndexPath *ip = nil;
  617. NSInteger dayCount = self.dayData.count;
  618. NSInteger relationalIndex = 0;
  619. CGFloat shiftIndex = 0.0;
  620. NSString *currentValue = nil;
  621. switch (type) {
  622. case KBTableViewTagHours:
  623. foundIndex = [self.hourData indexOfObject:value];
  624. if (foundIndex != NSNotFound){
  625. ip = [NSIndexPath indexPathForRow:[self startIndexForHours]+foundIndex inSection:0];
  626. //DPLog(@"found index: %lu", ip.row);
  627. [self.hourTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  628. [self.hourTable selectRowAtIndexPath:ip animated:animated scrollPosition:UITableViewScrollPositionTop];
  629. [self delayedUpdateFocus];
  630. }
  631. break;
  632. case KBTableViewTagMinutes:
  633. foundIndex = [self.minutesData indexOfObject:value];
  634. if (foundIndex != NSNotFound){
  635. ip = [NSIndexPath indexPathForRow:[self startIndexForMinutes]+foundIndex inSection:0];
  636. //DPLog(@"found index: %lu", ip.row);
  637. [self.minuteTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  638. [self.minuteTable selectRowAtIndexPath:ip animated:animated scrollPosition:UITableViewScrollPositionTop];
  639. [self delayedUpdateFocus];
  640. }
  641. break;
  642. case KBTableViewTagMonths:
  643. currentValue = self.monthTable.selectedValue;
  644. relationalIndex = [self.monthData indexOfObject:currentValue];
  645. foundIndex = [self.monthData indexOfObject:value];
  646. if (foundIndex != NSNotFound){
  647. shiftIndex = foundIndex - relationalIndex;
  648. if (self.monthTable.selectedIndexPath && currentValue){
  649. //DPLog(@"current value: %@ relationalIndex: %lu found index: %lu, shift index: %.0f", currentValue, relationalIndex, foundIndex, shiftIndex);
  650. ip = [NSIndexPath indexPathForRow:self.monthTable.selectedIndexPath.row+shiftIndex inSection:0];
  651. } else {
  652. ip = [NSIndexPath indexPathForRow:[self startIndexForHours]+foundIndex inSection:0];
  653. }
  654. [self.monthTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  655. [_monthTable selectRowAtIndexPath:ip animated:animated scrollPosition:UITableViewScrollPositionTop];
  656. [self delayedUpdateFocus];
  657. }
  658. break;
  659. case KBTableViewTagDays:
  660. foundIndex = [self.dayData indexOfObject:value];
  661. if (foundIndex != NSNotFound){
  662. ip = [NSIndexPath indexPathForRow:[self indexForDays:dayCount]+foundIndex inSection:0];
  663. //DPLog(@"found index: %lu", ip.row);
  664. [self.dayTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  665. [_dayTable selectRowAtIndexPath:ip animated:animated scrollPosition:UITableViewScrollPositionTop];
  666. [self delayedUpdateFocus];
  667. }
  668. break;
  669. case KBTableViewTagYears:
  670. foundIndex = [value integerValue];
  671. if (_minYear > 1){
  672. NSInteger intValue = [value integerValue];
  673. foundIndex = intValue - _minYear;
  674. }
  675. //DPLog(@"foundIndex: %lu from value:%@", foundIndex, value);
  676. ip = [NSIndexPath indexPathForRow:foundIndex inSection:0];
  677. [self.yearTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  678. [self delayedUpdateFocus];
  679. default:
  680. break;
  681. }
  682. }
  683. - (NSInteger)indexForDays:(NSInteger)days {
  684. switch (days) {
  685. case 28: return 24976;
  686. case 29: return 24969;
  687. case 30: return 24990;
  688. case 31: return 24986;
  689. }
  690. return 25000;
  691. }
  692. - (UITableViewCell *)infiniteCellForTableView:(KBTableView *)tableView atIndexPath:(NSIndexPath *)indexPath dataSource:(NSArray *)dataSource {
  693. static NSString *CellIdentifier = @"Cell";
  694. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  695. // Configure the cell...
  696. if (!cell) {
  697. cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
  698. }
  699. NSString *s = [dataSource objectAtIndex: indexPath.row % dataSource.count];
  700. [cell.textLabel setText: s];
  701. cell.textLabel.textAlignment = NSTextAlignmentCenter;
  702. return cell;
  703. }
  704. - (UITableViewCell *)amPMCellForRowAtIndexPath:(NSIndexPath *)indexPath {
  705. static NSString *CellIdentifier = @"amPMCell";
  706. UITableViewCell *cell = [_amPMTable dequeueReusableCellWithIdentifier:CellIdentifier];
  707. // Configure the cell...
  708. if (!cell) {
  709. cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
  710. }
  711. if (indexPath.row == 0){
  712. cell.textLabel.text = @"AM";
  713. } else {
  714. cell.textLabel.text = @"PM";
  715. }
  716. return cell;
  717. }
  718. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  719. UITableViewCell *cell = nil;
  720. if (tableView == _hourTable){
  721. return [self infiniteCellForTableView:(KBTableView*)tableView atIndexPath:indexPath dataSource:self.hourData];
  722. } else if (tableView == _minuteTable) {
  723. return [self infiniteCellForTableView:(KBTableView*)tableView atIndexPath:indexPath dataSource:self.minutesData];
  724. } else if (tableView == _amPMTable) {
  725. return [self amPMCellForRowAtIndexPath:indexPath];
  726. } else if (tableView == _monthTable) {
  727. return [self infiniteCellForTableView:(KBTableView*)tableView atIndexPath:indexPath dataSource:self.monthData];
  728. } else if (tableView == _dayTable){
  729. return [self infiniteCellForTableView:(KBTableView*)tableView atIndexPath:indexPath dataSource:self.dayData];
  730. } else {
  731. cell = [tableView dequeueReusableCellWithIdentifier:@"year"];
  732. if (!cell){
  733. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"year"];
  734. }
  735. if (_minYear > 1){
  736. cell.textLabel.text = [NSString kb_stringWithFormat:"%lu", _minYear+indexPath.row+1];
  737. } else {
  738. cell.textLabel.text = [NSString kb_stringWithFormat:"%lu", indexPath.row+1];
  739. }
  740. cell.textLabel.textAlignment = NSTextAlignmentCenter;
  741. }
  742. return cell;
  743. }
  744. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  745. }
  746. - (void)selectionOccured {
  747. if (self.itemSelectedBlock){
  748. self.itemSelectedBlock(self.date);
  749. }
  750. [self sendActionsForControlEvents:UIControlEventValueChanged];
  751. if (self.showDateLabel){
  752. self.datePickerLabel.hidden = false;
  753. NSDateFormatter *dateFormatter = [KBDatePickerView sharedDateFormatter];
  754. NSString *strDate = [dateFormatter stringFromDate:self.date];
  755. DPLog(@"strDate: %@", strDate); // Result: strDate: 2014/05/19 10:51:50
  756. self.datePickerLabel.text = strDate;
  757. } else {
  758. self.datePickerLabel.hidden = true;
  759. }
  760. }
  761. - (id)valueForTableViewSelectedCell:(KBTableView *)tableView {
  762. id data = nil;
  763. if (!tableView.selectedIndexPath){
  764. return data;
  765. }
  766. switch (tableView.tag) {
  767. case KBTableViewTagMinutes:
  768. data = [self.minutesData objectAtIndex: tableView.selectedIndexPath.row % self.minutesData.count];
  769. break;
  770. case KBTableViewTagHours:
  771. data = [self.hourData objectAtIndex: tableView.selectedIndexPath.row % self.hourData.count];
  772. break;
  773. case KBTableViewTagMonths:
  774. data = [self.monthData objectAtIndex:tableView.selectedIndexPath.row % self.monthData.count];
  775. break;
  776. default:
  777. break;
  778. }
  779. return data;
  780. }
  781. - (KBDatePickerMode)datePickerMode {
  782. return _datePickerMode;
  783. }
  784. - (void)setDatePickerMode:(KBDatePickerMode)datePickerMode {
  785. _datePickerMode = datePickerMode;
  786. [self adaptModeChange];
  787. }
  788. - (void)adaptModeChange {
  789. [self removeAllSubviews];
  790. [self layoutViews];
  791. }
  792. - (CGSize)sizeThatFits:(CGSize)size {
  793. //CGSize sup = [super sizeThatFits:size];
  794. return CGSizeMake([self widthForMode], STACK_VIEW_HEIGHT+81+60+80);
  795. }
  796. - (CGFloat)widthForMode {
  797. switch (self.datePickerMode) {
  798. case KBDatePickerModeDate: return 720;
  799. case KBDatePickerModeTime: return 500;
  800. case KBDatePickerModeDateAndTime: return 800;
  801. case KBDatePickerModeCountDownTimer: return 400;
  802. }
  803. return 720;
  804. }
  805. - (void)layoutViews {
  806. [self viewSetupForMode];
  807. if (!_tableViews){
  808. DPLog(@"no table views, bail!!");
  809. return;
  810. }
  811. if (_datePickerStackView != nil){
  812. [_datePickerStackView removeAllArrangedSubviews];
  813. [_datePickerStackView removeFromSuperview];
  814. _datePickerStackView = nil;
  815. }
  816. self.datePickerStackView = [[UIStackView alloc] initWithArrangedSubviews:_tableViews];
  817. self.datePickerStackView.translatesAutoresizingMaskIntoConstraints = false;
  818. self.datePickerStackView.spacing = 10;
  819. self.datePickerStackView.axis = UILayoutConstraintAxisHorizontal;
  820. self.datePickerStackView.alignment = UIStackViewAlignmentFill;
  821. self.datePickerStackView.distribution = UIStackViewDistributionFillEqually;
  822. self.widthConstraint = [self.datePickerStackView.widthAnchor constraintEqualToConstant:self.widthForMode];
  823. self.widthConstraint.active = true;
  824. [self.datePickerStackView.heightAnchor constraintEqualToConstant:STACK_VIEW_HEIGHT].active = true;
  825. [self addSubview:self.datePickerStackView];
  826. [self.datePickerStackView.centerXAnchor constraintEqualToAnchor:self.centerXAnchor].active = true;
  827. //[self.datePickerStackView.centerYAnchor constraintEqualToAnchor:self.centerYAnchor].active = true;
  828. self.datePickerLabel = [[UILabel alloc] init];
  829. self.datePickerLabel.translatesAutoresizingMaskIntoConstraints = false;
  830. self.datePickerLabel.hidden = !_showDateLabel;
  831. [self addSubview:self.datePickerLabel];
  832. [self.datePickerLabel.centerXAnchor constraintEqualToAnchor:self.centerXAnchor].active = true;
  833. [self.datePickerLabel.topAnchor constraintEqualToAnchor:self.datePickerStackView.bottomAnchor constant:80].active = true;
  834. [self setupLabelsForMode];
  835. [self.datePickerStackView.topAnchor constraintEqualToAnchor:self.dayLabel.bottomAnchor constant:20].active = true;
  836. [self scrollToCurrentDateAnimated:false];
  837. }
  838. @end