KBDatePickerView.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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.tag = KBTableViewTagAMPM;
  204. self.hourTable.delegate = self;
  205. self.hourTable.dataSource = self;
  206. self.minuteTable.delegate = self;
  207. self.minuteTable.dataSource = self;
  208. self.amPMTable.delegate = self;
  209. self.amPMTable.dataSource = self;
  210. _tableViews = @[_hourTable, _minuteTable, _amPMTable];
  211. }
  212. - (void)layoutForDate {
  213. if (self.monthLabel){
  214. [self.monthLabel removeFromSuperview];
  215. self.monthLabel = nil;
  216. [self.yearLabel removeFromSuperview];
  217. self.yearLabel = nil;
  218. [self.dayLabel removeFromSuperview];
  219. self.dayLabel = nil;
  220. self.monthTable = nil;
  221. self.yearTable = nil;
  222. self.dayTable = nil;
  223. _tableViews = nil;
  224. }
  225. [self populateDaysForCurrentMonth];
  226. [self populateYearsForDateRange];
  227. self.monthLabel = [[UILabel alloc] init];
  228. self.monthLabel.translatesAutoresizingMaskIntoConstraints = false;
  229. self.monthLabel.text = @"Month";
  230. self.yearLabel = [[UILabel alloc] init];
  231. self.yearLabel.translatesAutoresizingMaskIntoConstraints = false;
  232. self.yearLabel.text = @"Year";
  233. self.dayLabel = [[UILabel alloc] init];
  234. self.dayLabel.translatesAutoresizingMaskIntoConstraints = false;
  235. self.dayLabel.text = @"Day";
  236. self.monthTable = [[KBTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
  237. self.monthTable.tag = KBTableViewTagMonths;
  238. self.yearTable = [[KBTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
  239. self.yearTable.tag = KBTableViewTagYears;
  240. self.dayTable = [[KBTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
  241. self.dayTable.tag = KBTableViewTagDays;
  242. self.monthTable.delegate = self;
  243. self.monthTable.dataSource = self;
  244. self.yearTable.delegate = self;
  245. self.yearTable.dataSource = self;
  246. self.dayTable.delegate = self;
  247. self.dayTable.dataSource = self;
  248. _tableViews = @[_monthTable, _dayTable, _yearTable];
  249. [self addSubview:self.monthLabel];
  250. [self addSubview:self.yearLabel];
  251. [self addSubview:self.dayLabel];
  252. }
  253. - (void)layoutLabelsForDate {
  254. [self.monthLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:_topOffset].active = true;
  255. [self.dayLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:_topOffset].active = true;
  256. [self.dayLabel.centerXAnchor constraintEqualToAnchor:self.dayTable.centerXAnchor].active = true;
  257. [self.monthLabel.centerXAnchor constraintEqualToAnchor:self.monthTable.centerXAnchor].active = true;
  258. [self.yearLabel.centerXAnchor constraintEqualToAnchor:self.yearTable.centerXAnchor].active = true;
  259. [self.yearLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:_topOffset].active = true;
  260. [self.monthLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:_topOffset].active = true;
  261. }
  262. - (void)layoutUnsupportedView {
  263. if (_datePickerStackView != nil){
  264. [_datePickerStackView removeAllArrangedSubviews];
  265. [_datePickerStackView removeFromSuperview];
  266. _datePickerStackView = nil;
  267. }
  268. self.unsupportedLabel = [[UILabel alloc] init];
  269. [self addSubview:self.unsupportedLabel];
  270. self.unsupportedLabel.translatesAutoresizingMaskIntoConstraints = false;
  271. [self.unsupportedLabel.centerYAnchor constraintEqualToAnchor:self.centerYAnchor].active = true;
  272. [self.unsupportedLabel.centerXAnchor constraintEqualToAnchor:self.centerXAnchor].active = true;
  273. self.unsupportedLabel.text = [self kb_stringWithFormat:"Error: currently '%s' is an unsuppported configuration.", [NSStringFromKBDatePickerMode(self.datePickerMode) UTF8String]];
  274. }
  275. - (void)layoutForDateAndTime {
  276. [self layoutUnsupportedView];
  277. }
  278. - (void)layoutForCountdownTimer {
  279. [self layoutUnsupportedView];
  280. }
  281. - (void)layoutLabelsForTime {
  282. }
  283. - (void)setupLabelsForMode {
  284. switch (self.datePickerMode) {
  285. case KBDatePickerModeTime:
  286. [self layoutLabelsForTime];
  287. break;
  288. case KBDatePickerModeDate:
  289. [self layoutLabelsForDate];
  290. break;
  291. case KBDatePickerModeDateAndTime:
  292. [self layoutForDateAndTime];
  293. break;
  294. case KBDatePickerModeCountDownTimer:
  295. [self layoutForCountdownTimer];
  296. break;
  297. default:
  298. break;
  299. }
  300. }
  301. - (void)viewSetupForMode {
  302. if (self.unsupportedLabel){
  303. [self.unsupportedLabel removeFromSuperview];
  304. self.unsupportedLabel = nil;
  305. }
  306. switch (self.datePickerMode) {
  307. case KBDatePickerModeTime:
  308. [self layoutForTime];
  309. break;
  310. case KBDatePickerModeDate:
  311. [self layoutForDate];
  312. break;
  313. case KBDatePickerModeDateAndTime:
  314. [self layoutForDateAndTime];
  315. break;
  316. case KBDatePickerModeCountDownTimer:
  317. [self layoutForCountdownTimer];
  318. break;
  319. default:
  320. break;
  321. }
  322. }
  323. - (NSArray *)createNumberArray:(NSInteger)count zeroIndex:(BOOL)zeroIndex leadingZero:(BOOL)leadingZero {
  324. __block NSMutableArray *_newArray = [NSMutableArray new];
  325. int startIndex = 1;
  326. if (zeroIndex){
  327. startIndex = 0;
  328. }
  329. for (int i = startIndex; i < count+startIndex; i++){
  330. if (leadingZero){
  331. [_newArray addObject:[self kb_stringWithFormat:"%02i", i]];
  332. } else {
  333. [_newArray addObject:[self kb_stringWithFormat:"%i", i]];
  334. }
  335. }
  336. return _newArray;
  337. }
  338. - (NSArray *)monthData {
  339. return [[self calendar] monthSymbols];
  340. }
  341. - (void)scrollToCurrentDateAnimated:(BOOL)animated {
  342. if (self.datePickerMode == KBDatePickerModeTime){
  343. [self loadTimeFromDateAnimated:animated];
  344. } else {
  345. NSDateComponents *components = [self currentComponents:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay];
  346. NSInteger monthIndex = components.month-1;
  347. NSString *monthSymbol = self.monthData[monthIndex];
  348. if (![self.monthTable.selectedValue isEqualToString:monthSymbol]){
  349. [self scrollToValue:monthSymbol inTableViewType:KBTableViewTagMonths animated:animated];
  350. }
  351. NSInteger dayIndex = components.day;
  352. NSString *dayString = [self kb_stringWithFormat:"%i",dayIndex];
  353. if (![[_dayTable selectedValue] isEqualToString:dayString]){
  354. [self scrollToValue:dayString inTableViewType:KBTableViewTagDays animated:animated];
  355. }
  356. NSInteger yearIndex = components.year-1;
  357. //DPLog(@"year index: %lu", yearIndex);
  358. NSString *yearString = [self kb_stringWithFormat:"%i",yearIndex];
  359. //DPLog(@"year index: %@", yearString);
  360. if (![[_yearTable selectedValue] isEqualToString:yearString]){
  361. _yearSelected = yearIndex;
  362. [self scrollToValue:yearString inTableViewType:KBTableViewTagYears animated:animated];
  363. }
  364. //[_yearTable selectRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] animated:animated scrollPosition:UITableViewScrollPositionTop];
  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. //NSDateComponents *comp = [self currentComponents:NSCalendarUnitMonth];
  571. NSRange days = [[self calendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self.date];
  572. //DPLog(@"month : %lu days %lu for: %@", comp.month, days.length, self.date);
  573. _currentMonthDayCount = days.length; //this is used to push a date back if they've gone too far.
  574. if (!self.dayData){ //only need to populate it once
  575. self.dayData = [self createNumberArray:31 zeroIndex:false leadingZero:false];
  576. [self.dayTable reloadData];
  577. }
  578. //NSString *currentDay = [self kb_stringWithFormat:"%lu", _daySelected];
  579. //DPLog(@"_daySelected: %@ _yearTable.selectedValue: %@", currentDay, _yearTable.selectedValue);
  580. //[self scrollToValue:currentDay inTableViewType:KBTableViewTagDays animated:false];
  581. }
  582. - (void)setupTimeData {
  583. self.hourData = [self createNumberArray:12 zeroIndex:false leadingZero:false];
  584. self.minutesData = [self createNumberArray:60 zeroIndex:true leadingZero:true];
  585. }
  586. - (NSInteger)startIndexForHours {
  587. return 24996;
  588. }
  589. - (NSInteger)startIndexForMinutes {
  590. return 24000;
  591. }
  592. - (id)kb_stringWithFormat:(const char*) fmt,... {
  593. va_list args;
  594. char temp[2048];
  595. va_start(args, fmt);
  596. vsprintf(temp, fmt, args);
  597. va_end(args);
  598. return [[NSString alloc] initWithUTF8String:temp];
  599. }
  600. - (void)loadTimeFromDateAnimated:(BOOL)animated {
  601. NSDateComponents *components = [self currentComponents:NSCalendarUnitHour | NSCalendarUnitMinute];
  602. NSInteger hour = components.hour;
  603. NSInteger minutes = components.minute;
  604. BOOL isPM = (hour >= 12);
  605. if (isPM){
  606. _pmSelected = true;
  607. hour = hour-12;
  608. NSIndexPath *amPMIndex = [NSIndexPath indexPathForRow:1 inSection:0];
  609. [self.amPMTable scrollToRowAtIndexPath:amPMIndex atScrollPosition:UITableViewScrollPositionTop animated:false];
  610. }
  611. NSString *hourValue = [self kb_stringWithFormat:"%lu", hour];
  612. NSString *minuteValue = [self kb_stringWithFormat:"%lu", minutes];
  613. DPLog(@"hours %@ minutes %@", hourValue, minuteValue);
  614. if (![[self.hourTable selectedValue] isEqualToString:hourValue]){
  615. [self scrollToValue:hourValue inTableViewType:KBTableViewTagHours animated:animated];
  616. }
  617. if (![[self.minuteTable selectedValue] isEqualToString:minuteValue]){
  618. [self scrollToValue:minuteValue inTableViewType:KBTableViewTagMinutes animated:animated];
  619. }
  620. }
  621. - (void)delayedUpdateFocus {
  622. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  623. [self setNeedsFocusUpdate];
  624. [self updateFocusIfNeeded];
  625. });
  626. }
  627. - (void)scrollToValue:(id)value inTableViewType:(KBTableViewTag)type animated:(BOOL)animated {
  628. NSInteger foundIndex = NSNotFound;
  629. NSIndexPath *ip = nil;
  630. NSInteger dayCount = self.dayData.count;
  631. NSInteger relationalIndex = 0;
  632. CGFloat shiftIndex = 0.0;
  633. NSString *currentValue = nil;
  634. switch (type) {
  635. case KBTableViewTagHours:
  636. foundIndex = [self.hourData indexOfObject:value];
  637. if (foundIndex != NSNotFound){
  638. ip = [NSIndexPath indexPathForRow:[self startIndexForHours]+foundIndex inSection:0];
  639. //DPLog(@"found index: %lu", ip.row);
  640. [self.hourTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  641. [self.hourTable selectRowAtIndexPath:ip animated:animated scrollPosition:UITableViewScrollPositionTop];
  642. [self delayedUpdateFocus];
  643. }
  644. break;
  645. case KBTableViewTagMinutes:
  646. foundIndex = [self.minutesData indexOfObject:value];
  647. if (foundIndex != NSNotFound){
  648. ip = [NSIndexPath indexPathForRow:[self startIndexForMinutes]+foundIndex inSection:0];
  649. //DPLog(@"found index: %lu", ip.row);
  650. [self.minuteTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  651. [self.minuteTable selectRowAtIndexPath:ip animated:animated scrollPosition:UITableViewScrollPositionTop];
  652. [self delayedUpdateFocus];
  653. }
  654. break;
  655. case KBTableViewTagMonths:
  656. //value = "December";
  657. currentValue = self.monthTable.selectedValue; //March
  658. relationalIndex = [self.monthData indexOfObject:currentValue]; //2
  659. foundIndex = [self.monthData indexOfObject:value]; //11
  660. //11 - 2 = 9 : go up 9 indexes
  661. //2 - 11 = -9 : go back 9 indexes
  662. if (foundIndex != NSNotFound){
  663. shiftIndex = foundIndex - relationalIndex;
  664. if (self.monthTable.selectedIndexPath && currentValue){
  665. //DPLog(@"current value: %@ relationalIndex: %lu found index: %lu, shift index: %.0f", currentValue, relationalIndex, foundIndex, shiftIndex);
  666. ip = [NSIndexPath indexPathForRow:self.monthTable.selectedIndexPath.row+shiftIndex inSection:0];
  667. } else {
  668. ip = [NSIndexPath indexPathForRow:[self startIndexForHours]+foundIndex inSection:0];
  669. }
  670. [self.monthTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  671. [_monthTable selectRowAtIndexPath:ip animated:animated scrollPosition:UITableViewScrollPositionTop];
  672. [self delayedUpdateFocus];
  673. //[self.monthTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  674. }
  675. break;
  676. case KBTableViewTagDays:
  677. foundIndex = [self.dayData indexOfObject:value];
  678. if (foundIndex != NSNotFound){
  679. ip = [NSIndexPath indexPathForRow:[self indexForDays:dayCount]+foundIndex inSection:0];
  680. //DPLog(@"found index: %lu", ip.row);
  681. [self.dayTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  682. [_dayTable selectRowAtIndexPath:ip animated:animated scrollPosition:UITableViewScrollPositionTop];
  683. [self delayedUpdateFocus];
  684. }
  685. break;
  686. case KBTableViewTagYears:
  687. foundIndex = [value integerValue]; //FIXME: this will not work when custom min/max dates are set!
  688. if (_minYear > 1){
  689. NSInteger intValue = [value integerValue];
  690. foundIndex = intValue - _minYear;
  691. }
  692. //DPLog(@"foundIndex: %lu from value:%@", foundIndex, value);
  693. ip = [NSIndexPath indexPathForRow:foundIndex inSection:0];
  694. [self.yearTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:animated];
  695. [self delayedUpdateFocus];
  696. default:
  697. break;
  698. }
  699. }
  700. - (NSInteger)indexForDays:(NSInteger)days {
  701. switch (days) {
  702. case 28: return 24976;
  703. case 29: return 24969;
  704. case 30: return 24990;
  705. case 31: return 24986;
  706. }
  707. return 25000;
  708. }
  709. - (UITableViewCell *)infiniteCellForTableView:(KBTableView *)tableView atIndexPath:(NSIndexPath *)indexPath dataSource:(NSArray *)dataSource {
  710. static NSString *CellIdentifier = @"Cell";
  711. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  712. // Configure the cell...
  713. if (!cell) {
  714. cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
  715. }
  716. NSString *s = [dataSource objectAtIndex: indexPath.row % dataSource.count];
  717. [cell.textLabel setText: s];
  718. cell.textLabel.textAlignment = NSTextAlignmentCenter;
  719. return cell;
  720. }
  721. - (UITableViewCell *)amPMCellForRowAtIndexPath:(NSIndexPath *)indexPath {
  722. static NSString *CellIdentifier = @"amPMCell";
  723. UITableViewCell *cell = [_amPMTable dequeueReusableCellWithIdentifier:CellIdentifier];
  724. // Configure the cell...
  725. if (!cell) {
  726. cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
  727. }
  728. if (indexPath.row == 0){
  729. cell.textLabel.text = @"AM";
  730. } else {
  731. cell.textLabel.text = @"PM";
  732. }
  733. return cell;
  734. }
  735. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  736. UITableViewCell *cell = nil;
  737. if (tableView == _hourTable){
  738. return [self infiniteCellForTableView:(KBTableView*)tableView atIndexPath:indexPath dataSource:self.hourData];
  739. } else if (tableView == _minuteTable) {
  740. return [self infiniteCellForTableView:(KBTableView*)tableView atIndexPath:indexPath dataSource:self.minutesData];
  741. } else if (tableView == _amPMTable) {
  742. return [self amPMCellForRowAtIndexPath:indexPath];
  743. } else if (tableView == _monthTable) {
  744. return [self infiniteCellForTableView:(KBTableView*)tableView atIndexPath:indexPath dataSource:self.monthData];
  745. } else if (tableView == _dayTable){
  746. return [self infiniteCellForTableView:(KBTableView*)tableView atIndexPath:indexPath dataSource:self.dayData];
  747. } else {
  748. cell = [tableView dequeueReusableCellWithIdentifier:@"year"];
  749. if (!cell){
  750. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"year"];
  751. }
  752. //NSInteger year = [[self calendar] component:NSCalendarUnitYear fromDate:self.date];
  753. if (_minYear > 1){
  754. cell.textLabel.text = [self kb_stringWithFormat:"%lu", _minYear+indexPath.row+1];
  755. } else {
  756. cell.textLabel.text = [self kb_stringWithFormat:"%lu", indexPath.row+1];
  757. }
  758. //cell.textLabel.text = [NSString stringWithFormat:@"%lu", year - 1 + indexPath.row];
  759. cell.textLabel.textAlignment = NSTextAlignmentCenter;
  760. }
  761. return cell;
  762. }
  763. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  764. }
  765. - (void)selectionOccured {
  766. if (self.itemSelectedBlock){
  767. self.itemSelectedBlock(self.date);
  768. }
  769. [self sendActionsForControlEvents:UIControlEventValueChanged];
  770. if (self.showDateLabel){
  771. self.datePickerLabel.hidden = false;
  772. NSDateFormatter *dateFormatter = [KBDatePickerView sharedDateFormatter];
  773. NSString *strDate = [dateFormatter stringFromDate:self.date];
  774. DPLog(@"strDate: %@", strDate); // Result: strDate: 2014/05/19 10:51:50
  775. self.datePickerLabel.text = strDate;
  776. //self.datePickerLabel.text = self.date.description;
  777. } else {
  778. self.datePickerLabel.hidden = true;
  779. }
  780. }
  781. - (id)valueForTableViewSelectedCell:(KBTableView *)tableView {
  782. id data = nil;
  783. if (!tableView.selectedIndexPath){
  784. return data;
  785. }
  786. switch (tableView.tag) {
  787. case KBTableViewTagMinutes:
  788. data = [self.minutesData objectAtIndex: tableView.selectedIndexPath.row % self.minutesData.count];
  789. break;
  790. case KBTableViewTagHours:
  791. data = [self.hourData objectAtIndex: tableView.selectedIndexPath.row % self.hourData.count];
  792. break;
  793. case KBTableViewTagMonths:
  794. data = [self.monthData objectAtIndex:tableView.selectedIndexPath.row % self.monthData.count];
  795. break;
  796. default:
  797. break;
  798. }
  799. return data;
  800. }
  801. - (KBDatePickerMode)datePickerMode {
  802. return _datePickerMode;
  803. }
  804. - (void)setDatePickerMode:(KBDatePickerMode)datePickerMode {
  805. _datePickerMode = datePickerMode;
  806. [self adaptModeChange];
  807. }
  808. - (void)adaptModeChange {
  809. [self removeAllSubviews];
  810. [self layoutViews];
  811. }
  812. - (CGSize)sizeThatFits:(CGSize)size {
  813. //CGSize sup = [super sizeThatFits:size];
  814. return CGSizeMake([self widthForMode], STACK_VIEW_HEIGHT+81+60+80);
  815. }
  816. - (CGFloat)widthForMode {
  817. switch (self.datePickerMode) {
  818. case KBDatePickerModeDate: return 720;
  819. case KBDatePickerModeTime: return 500;
  820. case KBDatePickerModeDateAndTime: return 800;
  821. case KBDatePickerModeCountDownTimer: return 400;
  822. }
  823. return 720;
  824. }
  825. - (void)layoutViews {
  826. [self viewSetupForMode];
  827. if (!_tableViews){
  828. DPLog(@"no table views, bail!!");
  829. return;
  830. }
  831. if (_datePickerStackView != nil){
  832. [_datePickerStackView removeAllArrangedSubviews];
  833. [_datePickerStackView removeFromSuperview];
  834. _datePickerStackView = nil;
  835. }
  836. self.datePickerStackView = [[UIStackView alloc] initWithArrangedSubviews:_tableViews];
  837. self.datePickerStackView.translatesAutoresizingMaskIntoConstraints = false;
  838. self.datePickerStackView.spacing = 10;
  839. self.datePickerStackView.axis = UILayoutConstraintAxisHorizontal;
  840. self.datePickerStackView.alignment = UIStackViewAlignmentFill;
  841. self.datePickerStackView.distribution = UIStackViewDistributionFillEqually;
  842. self.widthConstraint = [self.datePickerStackView.widthAnchor constraintEqualToConstant:self.widthForMode];
  843. self.widthConstraint.active = true;
  844. [self.datePickerStackView.heightAnchor constraintEqualToConstant:STACK_VIEW_HEIGHT].active = true;
  845. [self addSubview:self.datePickerStackView];
  846. [self.datePickerStackView.centerXAnchor constraintEqualToAnchor:self.centerXAnchor].active = true;
  847. //[self.datePickerStackView.centerYAnchor constraintEqualToAnchor:self.centerYAnchor].active = true;
  848. self.datePickerLabel = [[UILabel alloc] init];
  849. self.datePickerLabel.translatesAutoresizingMaskIntoConstraints = false;
  850. self.datePickerLabel.hidden = !_showDateLabel;
  851. [self addSubview:self.datePickerLabel];
  852. [self.datePickerLabel.centerXAnchor constraintEqualToAnchor:self.centerXAnchor].active = true;
  853. [self.datePickerLabel.topAnchor constraintEqualToAnchor:self.datePickerStackView.bottomAnchor constant:80].active = true;
  854. [self setupLabelsForMode];
  855. [self.datePickerStackView.topAnchor constraintEqualToAnchor:self.dayLabel.bottomAnchor constant:20].active = true;
  856. [self scrollToCurrentDateAnimated:false];
  857. }
  858. @end