KBDatePickerView.m 37 KB

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