FLEXTableViewController.m 14 KB

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