KBDatePickerView.m 36 KB

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