FLEXTableViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. //
  2. // FLEXTableViewController.m
  3. // FLEX
  4. //
  5. // Created by Tanner on 7/5/19.
  6. // Copyright © 2019 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXTableViewController.h"
  9. #import "FLEXScopeCarousel.h"
  10. #import "FLEXTableView.h"
  11. #import "FLEXUtility.h"
  12. #import <objc/runtime.h>
  13. @interface Block : NSObject
  14. - (void)invoke;
  15. @end
  16. CGFloat const kFLEXDebounceInstant = 0.f;
  17. CGFloat const kFLEXDebounceFast = 0.05;
  18. CGFloat const kFLEXDebounceForAsyncSearch = 0.15;
  19. CGFloat const kFLEXDebounceForExpensiveIO = 0.5;
  20. @interface FLEXTableViewController ()
  21. @property (nonatomic) NSTimer *debounceTimer;
  22. @property (nonatomic) BOOL didInitiallyRevealSearchBar;
  23. @property (nonatomic) UITableViewStyle style;
  24. @property (nonatomic, readonly) UIView *tableHeaderViewContainer;
  25. @end
  26. @implementation FLEXTableViewController
  27. @synthesize tableHeaderViewContainer = _tableHeaderViewContainer;
  28. @synthesize automaticallyShowsSearchBarCancelButton = _automaticallyShowsSearchBarCancelButton;
  29. #pragma mark - Public
  30. - (id)init {
  31. #if FLEX_AT_LEAST_IOS13_SDK
  32. if (@available(iOS 13.0, *)) {
  33. self = [self initWithStyle:UITableViewStyleInsetGrouped];
  34. } else {
  35. self = [self initWithStyle:UITableViewStyleGrouped];
  36. }
  37. #else
  38. self = [self initWithStyle:UITableViewStyleGrouped];
  39. #endif
  40. return self;
  41. }
  42. - (id)initWithStyle:(UITableViewStyle)style {
  43. self = [super initWithStyle:style];
  44. if (self) {
  45. _searchBarDebounceInterval = kFLEXDebounceFast;
  46. _showSearchBarInitially = YES;
  47. _style = style;
  48. }
  49. return self;
  50. }
  51. - (FLEXWindow *)window {
  52. return (id)self.view.window;
  53. }
  54. - (void)setShowsSearchBar:(BOOL)showsSearchBar {
  55. if (_showsSearchBar == showsSearchBar) return;
  56. _showsSearchBar = showsSearchBar;
  57. if (showsSearchBar) {
  58. UIViewController *results = self.searchResultsController;
  59. self.searchController = [[UISearchController alloc] initWithSearchResultsController:results];
  60. self.searchController.searchBar.placeholder = @"Filter";
  61. self.searchController.searchResultsUpdater = (id)self;
  62. self.searchController.delegate = (id)self;
  63. self.searchController.dimsBackgroundDuringPresentation = NO;
  64. self.searchController.hidesNavigationBarDuringPresentation = NO;
  65. /// Not necessary in iOS 13; remove this when iOS 13 is the minimum deployment target
  66. self.searchController.searchBar.delegate = self;
  67. self.automaticallyShowsSearchBarCancelButton = YES;
  68. #if FLEX_AT_LEAST_IOS13_SDK
  69. if (@available(iOS 13, *)) {
  70. self.searchController.automaticallyShowsScopeBar = NO;
  71. }
  72. #endif
  73. [self addSearchController:self.searchController];
  74. } else {
  75. // Search already shown and just set to NO, so remove it
  76. [self removeSearchController:self.searchController];
  77. }
  78. }
  79. - (void)setShowsCarousel:(BOOL)showsCarousel {
  80. if (_showsCarousel == showsCarousel) return;
  81. _showsCarousel = showsCarousel;
  82. if (showsCarousel) {
  83. _carousel = ({
  84. __weak __typeof(self) weakSelf = self;
  85. FLEXScopeCarousel *carousel = [FLEXScopeCarousel new];
  86. carousel.selectedIndexChangedAction = ^(NSInteger idx) {
  87. __typeof(self) self = weakSelf;
  88. [self updateSearchResults:self.searchText];
  89. };
  90. // UITableView won't update the header size unless you reset the header view
  91. [carousel registerBlockForDynamicTypeChanges:^(FLEXScopeCarousel *carousel) {
  92. __typeof(self) self = weakSelf;
  93. [self layoutTableHeaderIfNeeded];
  94. }];
  95. carousel;
  96. });
  97. [self addCarousel:_carousel];
  98. } else {
  99. // Carousel already shown and just set to NO, so remove it
  100. [self removeCarousel:_carousel];
  101. }
  102. }
  103. - (NSInteger)selectedScope {
  104. if (self.searchController.searchBar.showsScopeBar) {
  105. return self.searchController.searchBar.selectedScopeButtonIndex;
  106. } else if (self.showsCarousel) {
  107. return self.carousel.selectedIndex;
  108. } else {
  109. return NSNotFound;
  110. }
  111. }
  112. - (void)setSelectedScope:(NSInteger)selectedScope {
  113. if (self.searchController.searchBar.showsScopeBar) {
  114. self.searchController.searchBar.selectedScopeButtonIndex = selectedScope;
  115. } else if (self.showsCarousel) {
  116. self.carousel.selectedIndex = selectedScope;
  117. }
  118. [self updateSearchResults:self.searchText];
  119. }
  120. - (NSString *)searchText {
  121. return self.searchController.searchBar.text;
  122. }
  123. - (BOOL)automaticallyShowsSearchBarCancelButton {
  124. #if FLEX_AT_LEAST_IOS13_SDK
  125. if (@available(iOS 13, *)) {
  126. return self.searchController.automaticallyShowsCancelButton;
  127. }
  128. #endif
  129. return _automaticallyShowsSearchBarCancelButton;
  130. }
  131. - (void)setAutomaticallyShowsSearchBarCancelButton:(BOOL)value {
  132. #if FLEX_AT_LEAST_IOS13_SDK
  133. if (@available(iOS 13, *)) {
  134. self.searchController.automaticallyShowsCancelButton = value;
  135. }
  136. #endif
  137. _automaticallyShowsSearchBarCancelButton = value;
  138. }
  139. - (void)updateSearchResults:(NSString *)newText { }
  140. - (void)onBackgroundQueue:(NSArray *(^)(void))backgroundBlock thenOnMainQueue:(void(^)(NSArray *))mainBlock {
  141. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  142. NSArray *items = backgroundBlock();
  143. dispatch_async(dispatch_get_main_queue(), ^{
  144. mainBlock(items);
  145. });
  146. });
  147. }
  148. #pragma mark - View Controller Lifecycle
  149. - (void)loadView {
  150. self.view = [FLEXTableView style:self.style];
  151. self.tableView.dataSource = self;
  152. self.tableView.delegate = self;
  153. }
  154. - (void)viewDidLoad {
  155. [super viewDidLoad];
  156. self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
  157. // On iOS 13, the root view controller shows it's search bar no matter what.
  158. // Turning this off avoids some weird flash the navigation bar does when we
  159. // toggle navigationItem.hidesSearchBarWhenScrolling on and off. The flash
  160. // will still happen on subsequent view controllers, but we can at least
  161. // avoid it for the root view controller
  162. if (@available(iOS 13, *)) {
  163. if (self.navigationController.viewControllers.firstObject == self) {
  164. _showSearchBarInitially = NO;
  165. }
  166. }
  167. }
  168. - (void)viewWillLayoutSubviews {
  169. [super viewWillLayoutSubviews];
  170. }
  171. - (void)viewWillAppear:(BOOL)animated {
  172. [super viewWillAppear:animated];
  173. // When going back, make the search bar reappear instead of hiding
  174. if (@available(iOS 11.0, *)) {
  175. if ((self.pinSearchBar || self.showSearchBarInitially) && !self.didInitiallyRevealSearchBar) {
  176. self.navigationItem.hidesSearchBarWhenScrolling = NO;
  177. }
  178. }
  179. }
  180. - (void)viewDidAppear:(BOOL)animated {
  181. [super viewDidAppear:animated];
  182. // Allow scrolling to collapse the search bar, only if we don't want it pinned
  183. if (@available(iOS 11.0, *)) {
  184. if (self.showSearchBarInitially && !self.pinSearchBar && !self.didInitiallyRevealSearchBar) {
  185. // All this mumbo jumbo is necessary to work around a bug in iOS 13 up to 13.2
  186. // wherein quickly toggling navigationItem.hidesSearchBarWhenScrolling to make
  187. // the search bar appear initially results in a bugged search bar that
  188. // becomes transparent and floats over the screen as you scroll
  189. [UIView animateWithDuration:0.2 animations:^{
  190. self.navigationItem.hidesSearchBarWhenScrolling = YES;
  191. [self.navigationController.view setNeedsLayout];
  192. [self.navigationController.view layoutIfNeeded];
  193. }];
  194. }
  195. }
  196. // We only want to reveal the search bar when the view controller first appears.
  197. self.didInitiallyRevealSearchBar = YES;
  198. }
  199. - (void)willMoveToParentViewController:(UIViewController *)parent {
  200. [super willMoveToParentViewController:parent];
  201. // Reset this since we are re-appearing under a new
  202. // parent view controller and need to show it again
  203. self.didInitiallyRevealSearchBar = NO;
  204. }
  205. #pragma mark - Private
  206. - (void)debounce:(void(^)(void))block {
  207. [self.debounceTimer invalidate];
  208. self.debounceTimer = [NSTimer
  209. scheduledTimerWithTimeInterval:self.searchBarDebounceInterval
  210. target:block
  211. selector:@selector(invoke)
  212. userInfo:nil
  213. repeats:NO
  214. ];
  215. }
  216. - (void)layoutTableHeaderIfNeeded {
  217. if (self.showsCarousel) {
  218. self.carousel.frame = FLEXRectSetHeight(
  219. self.carousel.frame, self.carousel.intrinsicContentSize.height
  220. );
  221. }
  222. self.tableView.tableHeaderView = self.tableView.tableHeaderView;
  223. [self.tableView layoutIfNeeded];
  224. }
  225. - (void)addCarousel:(FLEXScopeCarousel *)carousel {
  226. if (@available(iOS 11.0, *)) {
  227. self.tableView.tableHeaderView = carousel;
  228. } else {
  229. carousel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
  230. CGRect frame = self.tableHeaderViewContainer.frame;
  231. CGRect subviewFrame = carousel.frame;
  232. subviewFrame.origin.y = 0;
  233. // Put the carousel below the search bar if it's already there
  234. if (self.showsSearchBar) {
  235. carousel.frame = subviewFrame = FLEXRectSetY(
  236. subviewFrame, self.searchController.searchBar.frame.size.height
  237. );
  238. frame.size.height += carousel.intrinsicContentSize.height;
  239. } else {
  240. frame.size.height = carousel.intrinsicContentSize.height;
  241. }
  242. self.tableHeaderViewContainer.frame = frame;
  243. [self.tableHeaderViewContainer addSubview:carousel];
  244. }
  245. [self layoutTableHeaderIfNeeded];
  246. }
  247. - (void)removeCarousel:(FLEXScopeCarousel *)carousel {
  248. [carousel removeFromSuperview];
  249. if (@available(iOS 11.0, *)) {
  250. self.tableView.tableHeaderView = nil;
  251. } else {
  252. if (self.showsSearchBar) {
  253. [self removeSearchController:self.searchController];
  254. [self addSearchController:self.searchController];
  255. } else {
  256. self.tableView.tableHeaderView = nil;
  257. _tableHeaderViewContainer = nil;
  258. }
  259. }
  260. }
  261. - (void)addSearchController:(UISearchController *)controller {
  262. if (@available(iOS 11.0, *)) {
  263. self.navigationItem.searchController = controller;
  264. } else {
  265. controller.searchBar.autoresizingMask |= UIViewAutoresizingFlexibleBottomMargin;
  266. [self.tableHeaderViewContainer addSubview:controller.searchBar];
  267. CGRect subviewFrame = controller.searchBar.frame;
  268. CGRect frame = self.tableHeaderViewContainer.frame;
  269. frame.size.width = MAX(frame.size.width, subviewFrame.size.width);
  270. frame.size.height = subviewFrame.size.height;
  271. // Move the carousel down if it's already there
  272. if (self.showsCarousel) {
  273. self.carousel.frame = FLEXRectSetY(
  274. self.carousel.frame, subviewFrame.size.height
  275. );
  276. frame.size.height += self.carousel.frame.size.height;
  277. }
  278. self.tableHeaderViewContainer.frame = frame;
  279. [self layoutTableHeaderIfNeeded];
  280. }
  281. }
  282. - (void)removeSearchController:(UISearchController *)controller {
  283. if (@available(iOS 11.0, *)) {
  284. self.navigationItem.searchController = nil;
  285. } else {
  286. [controller.searchBar removeFromSuperview];
  287. if (self.showsCarousel) {
  288. // self.carousel.frame = FLEXRectRemake(CGPointZero, self.carousel.frame.size);
  289. [self removeCarousel:self.carousel];
  290. [self addCarousel:self.carousel];
  291. } else {
  292. self.tableView.tableHeaderView = nil;
  293. _tableHeaderViewContainer = nil;
  294. }
  295. }
  296. }
  297. - (UIView *)tableHeaderViewContainer {
  298. if (!_tableHeaderViewContainer) {
  299. _tableHeaderViewContainer = [UIView new];
  300. self.tableView.tableHeaderView = self.tableHeaderViewContainer;
  301. }
  302. return _tableHeaderViewContainer;
  303. }
  304. #pragma mark - Search Bar
  305. #pragma mark UISearchResultsUpdating
  306. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
  307. [self.debounceTimer invalidate];
  308. NSString *text = searchController.searchBar.text;
  309. void (^updateSearchResults)() = ^{
  310. if (self.searchResultsUpdater) {
  311. [self.searchResultsUpdater updateSearchResults:text];
  312. } else {
  313. [self updateSearchResults:text];
  314. }
  315. };
  316. // Only debounce if we want to, and if we have a non-empty string
  317. // Empty string events are sent instantly
  318. if (text.length && self.searchBarDebounceInterval > kFLEXDebounceInstant) {
  319. [self debounce:updateSearchResults];
  320. } else {
  321. updateSearchResults();
  322. }
  323. }
  324. #pragma mark UISearchControllerDelegate
  325. - (void)willPresentSearchController:(UISearchController *)searchController {
  326. // Manually show cancel button for < iOS 13
  327. if (!@available(iOS 13, *) && self.automaticallyShowsSearchBarCancelButton) {
  328. [searchController.searchBar setShowsCancelButton:YES animated:YES];
  329. }
  330. }
  331. - (void)willDismissSearchController:(UISearchController *)searchController {
  332. // Manually hide cancel button for < iOS 13
  333. if (!@available(iOS 13, *) && self.automaticallyShowsSearchBarCancelButton) {
  334. [searchController.searchBar setShowsCancelButton:NO animated:YES];
  335. }
  336. }
  337. #pragma mark UISearchBarDelegate
  338. /// Not necessary in iOS 13; remove this when iOS 13 is the deployment target
  339. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope {
  340. [self updateSearchResultsForSearchController:self.searchController];
  341. }
  342. #pragma mark Table view
  343. /// Not having a title in the first section looks weird with a rounded-corner table view style
  344. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  345. if (@available(iOS 13, *)) {
  346. if (self.style == UITableViewStyleInsetGrouped) {
  347. return @" ";
  348. }
  349. }
  350. return nil; // For plain/gropued style
  351. }
  352. @end