AHKActionSheet.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. //
  2. // AHKActionSheet.m
  3. // AHKActionSheetExample
  4. //
  5. // Created by Arkadiusz on 08-04-14.
  6. // Copyright (c) 2014 Arkadiusz Holko. All rights reserved.
  7. //
  8. // Modify by Marino Faggiana on 11/01/17.
  9. // Copyright (c) 2017 TWS. All rights reserved.
  10. //
  11. // Author Marino Faggiana <m.faggiana@twsweb.it>
  12. //
  13. #import <QuartzCore/QuartzCore.h>
  14. #import "AHKActionSheet.h"
  15. #import "AHKActionSheetViewController.h"
  16. #import "UIImage+AHKAdditions.h"
  17. #import "UIWindow+AHKAdditions.h"
  18. static const NSTimeInterval kDefaultAnimationDuration = 0.2f;
  19. // Length of the range at which the blurred background is being hidden when the user scrolls the tableView to the top.
  20. static const CGFloat kBlurFadeRangeSize = 200.0f;
  21. static NSString * const kCellIdentifier = @"Cell";
  22. // How much user has to scroll beyond the top of the tableView for the view to dismiss automatically.
  23. static const CGFloat kAutoDismissOffset = 80.0f;
  24. // Offset at which there's a check if the user is flicking the tableView down.
  25. static const CGFloat kFlickDownHandlingOffset = 20.0f;
  26. static const CGFloat kFlickDownMinVelocity = 2000.0f;
  27. // How much free space to leave at the top (above the tableView's contents) when there's a lot of elements. It makes this control look similar to the UIActionSheet.
  28. static const CGFloat kTopSpaceMarginFraction = 0.0f;
  29. // cancelButton's shadow height as the ratio to the cancelButton's height
  30. static const CGFloat kSpaceDivide = 5.0f;
  31. // width iPhone 7 Plus
  32. static const CGFloat maxWidth = 414.0f;
  33. /// Used for storing button configuration.
  34. @interface AHKActionSheetItem : NSObject
  35. @property (copy, nonatomic) NSString *title;
  36. @property (strong, nonatomic) UIImage *image;
  37. @property (nonatomic) AHKActionSheetButtonType type;
  38. @property (strong, nonatomic) AHKActionSheetHandler handler;
  39. @property (nonatomic, strong) UIColor *backgroundColor;
  40. @property (nonatomic) CGFloat height;
  41. @end
  42. @implementation AHKActionSheetItem
  43. @end
  44. @interface AHKActionSheet() <UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate>
  45. @property (strong, nonatomic) NSMutableArray *items;
  46. @property (weak, nonatomic, readwrite) UIWindow *previousKeyWindow;
  47. @property (strong, nonatomic) UIWindow *window;
  48. @property (weak, nonatomic) UIImageView *blurredBackgroundView;
  49. @property (weak, nonatomic) UITableView *tableView;
  50. @property (weak, nonatomic) UIButton *cancelButton;
  51. @property (weak, nonatomic) UIView *cancelButtonShadowView;
  52. @end
  53. @implementation AHKActionSheet
  54. #pragma mark - Init
  55. + (void)initialize
  56. {
  57. if (self != [AHKActionSheet class]) {
  58. return;
  59. }
  60. AHKActionSheet *appearance = [self appearance];
  61. [appearance setBlurRadius:0.0f];
  62. [appearance setBlurTintColor:[UIColor colorWithWhite:0.0f alpha:0.5f]];
  63. [appearance setBlurSaturationDeltaFactor:1.8f];
  64. [appearance setButtonHeight:50.0f];
  65. [appearance setSeparatorHeight:5.0f];
  66. [appearance setCancelButtonHeight:44.0f];
  67. [appearance setAutomaticallyTintButtonImages:@YES];
  68. [appearance setCancelButtonTextAttributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:17.0f], NSForegroundColorAttributeName : [UIColor darkGrayColor] }];
  69. [appearance setButtonTextAttributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:17.0f]}];
  70. [appearance setDisableButtonTextAttributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:17.0f]}];
  71. [appearance setDestructiveButtonTextAttributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:17.0f], NSForegroundColorAttributeName : [UIColor redColor] }];
  72. [appearance setTitleTextAttributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName : [UIColor grayColor] }];
  73. [appearance setCancelOnPanGestureEnabled:@(NO)];
  74. [appearance setCancelOnTapEmptyAreaEnabled:@(YES)];
  75. [appearance setAnimationDuration:kDefaultAnimationDuration];
  76. }
  77. - (instancetype)initWithTitle:(NSString *)title
  78. {
  79. self = [super init];
  80. if (self) {
  81. _title = [title copy];
  82. _cancelButtonTitle = @"Cancel";
  83. }
  84. return self;
  85. }
  86. - (instancetype)initWithView:(UIView *)view title:(NSString *)title
  87. {
  88. self = [super init];
  89. if (self) {
  90. _title = [title copy];
  91. _cancelButtonTitle = @"Cancel";
  92. _view = view;
  93. }
  94. return self;
  95. }
  96. - (instancetype)init
  97. {
  98. return [self initWithTitle:nil];
  99. }
  100. - (void)dealloc
  101. {
  102. self.tableView.dataSource = nil;
  103. self.tableView.delegate = nil;
  104. }
  105. #pragma mark - UITableViewDataSource
  106. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  107. {
  108. return 1;
  109. }
  110. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  111. {
  112. return (NSInteger)[self.items count];
  113. }
  114. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  115. {
  116. UITableViewCell *cell;
  117. if (cell == nil)
  118. cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];
  119. //cell.selectionStyle = UITableViewCellSelectionStyleNone;
  120. AHKActionSheetItem *item = self.items[(NSUInteger)indexPath.row];
  121. NSDictionary *attributes = nil;
  122. switch (item.type)
  123. {
  124. case AHKActionSheetButtonTypeDefault:
  125. attributes = self.buttonTextAttributes;
  126. break;
  127. case AHKActionSheetButtonTypeDisabled:
  128. attributes = self.disableButtonTextAttributes;
  129. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  130. break;
  131. case AHKActionSheetButtonTypeDestructive:
  132. attributes = self.destructiveButtonTextAttributes;
  133. break;
  134. case AHKActionSheetButtonTypeEncrypted:
  135. attributes = self.encryptedButtonTextAttributes;
  136. break;
  137. }
  138. UIImageView *imageView;
  139. if (item.type == AHKActionSheetButtonTypeDisabled) {
  140. imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15, _buttonHeight/2 - (30/2), 30, 30)];
  141. imageView.backgroundColor = [UIColor clearColor];
  142. [imageView setImage:item.image];
  143. } else {
  144. imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15, _buttonHeight/2 - (25/2), 25, 25)];
  145. BOOL useTemplateMode = [UIImage instancesRespondToSelector:@selector(imageWithRenderingMode:)] && [self.automaticallyTintButtonImages boolValue];
  146. imageView.image = useTemplateMode ? [item.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] : item.image;
  147. if ([UIImageView instancesRespondToSelector:@selector(tintColor)]){
  148. imageView.tintColor = attributes[NSForegroundColorAttributeName] ? attributes[NSForegroundColorAttributeName] : [UIColor blackColor];
  149. }
  150. }
  151. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.size.height + 5 , 0, cell.frame.size.width - cell.frame.size.height - 20, cell.frame.size.height)];
  152. NSAttributedString *attrTitle = [[NSAttributedString alloc] initWithString:item.title attributes:attributes];
  153. label.text = [NSString stringWithFormat: @"test"];
  154. label.numberOfLines = 0;
  155. label.attributedText = attrTitle;
  156. label.textAlignment = [self.buttonTextCenteringEnabled boolValue] ? NSTextAlignmentCenter : NSTextAlignmentLeft;
  157. cell.backgroundColor = item.backgroundColor;
  158. cell.selectedBackgroundView = [self createBackgroundView:tableView cell:cell forRowAtIndexPath:indexPath color:self.separatorColor];
  159. for (UIView *subview in [cell.contentView subviews])
  160. [subview removeFromSuperview];
  161. [cell.contentView addSubview:imageView];
  162. [cell.contentView addSubview:label];
  163. return cell;
  164. }
  165. #pragma mark - UITableViewDelegate
  166. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  167. {
  168. AHKActionSheetItem *item = self.items[(NSUInteger)indexPath.row];
  169. if (item.type != AHKActionSheetButtonTypeDisabled) {
  170. [self dismissAnimated:YES duration:self.animationDuration completion:item.handler];
  171. }
  172. }
  173. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  174. {
  175. AHKActionSheetItem *item = self.items[(NSUInteger)indexPath.row];
  176. return item.height;
  177. }
  178. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  179. {
  180. AHKActionSheetItem *item = self.items[(NSUInteger)indexPath.row];
  181. cell.backgroundView = [self createBackgroundView:tableView cell:cell forRowAtIndexPath:indexPath color:item.backgroundColor];
  182. }
  183. - (UIView *)createBackgroundView:(UITableView *)tableView cell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath color:(UIColor *)color
  184. {
  185. CGFloat cornerRadius = 10.f;
  186. cell.backgroundColor = UIColor.clearColor;
  187. CAShapeLayer *layer = [[CAShapeLayer alloc] init];
  188. CGMutablePathRef pathRef = CGPathCreateMutable();
  189. CGRect bounds = CGRectInset(cell.bounds, 10, 0);
  190. BOOL addLine = NO;
  191. if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
  192. CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
  193. } else if (indexPath.row == 0) {
  194. CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
  195. CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
  196. CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
  197. CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
  198. addLine = YES;
  199. } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
  200. CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
  201. CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
  202. CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
  203. CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
  204. } else {
  205. CGPathAddRect(pathRef, nil, bounds);
  206. addLine = YES;
  207. }
  208. if (addLine == YES) {
  209. CALayer *lineLayer = [[CALayer alloc] init];
  210. CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
  211. lineLayer.frame = CGRectMake(CGRectGetMinX(bounds), bounds.size.height-lineHeight, bounds.size.width, lineHeight);
  212. lineLayer.backgroundColor = tableView.separatorColor.CGColor;
  213. [layer addSublayer:lineLayer];
  214. }
  215. layer.path = pathRef;
  216. CFRelease(pathRef);
  217. layer.fillColor = color.CGColor;
  218. UIView *testView = [[UIView alloc] initWithFrame:bounds];
  219. [testView.layer insertSublayer:layer atIndex:0];
  220. testView.backgroundColor = UIColor.clearColor;
  221. return testView;
  222. }
  223. #pragma mark - UIScrollViewDelegate
  224. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  225. {
  226. if (![self.cancelOnPanGestureEnabled boolValue]) {
  227. return;
  228. }
  229. [self fadeBlursOnScrollToTop];
  230. }
  231. - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
  232. {
  233. if (![self.cancelOnPanGestureEnabled boolValue]) {
  234. return;
  235. }
  236. CGPoint scrollVelocity = [scrollView.panGestureRecognizer velocityInView:self];
  237. BOOL viewWasFlickedDown = scrollVelocity.y > kFlickDownMinVelocity && scrollView.contentOffset.y < -self.tableView.contentInset.top - kFlickDownHandlingOffset;
  238. BOOL shouldSlideDown = scrollView.contentOffset.y < -self.tableView.contentInset.top - kAutoDismissOffset;
  239. if (viewWasFlickedDown) {
  240. // use a shorter duration for a flick down animation
  241. static const NSTimeInterval duration = 0.2f;
  242. [self dismissAnimated:YES duration:duration completion:self.cancelHandler];
  243. } else if (shouldSlideDown) {
  244. [self dismissAnimated:YES duration:self.animationDuration completion:self.cancelHandler];
  245. }
  246. }
  247. #pragma mark - Properties
  248. - (NSMutableArray *)items
  249. {
  250. if (!_items) {
  251. _items = [NSMutableArray array];
  252. }
  253. return _items;
  254. }
  255. #pragma mark - Actions
  256. - (void)cancelButtonTapped:(id)sender
  257. {
  258. [self dismissAnimated:YES duration:self.animationDuration completion:self.cancelHandler];
  259. }
  260. #pragma mark - Public
  261. - (void)addButtonWithTitle:(NSString *)title image:(UIImage *)image backgroundColor:(UIColor *)backgroundColor height:(CGFloat)height type:(AHKActionSheetButtonType)type handler:(AHKActionSheetHandler)handler
  262. {
  263. AHKActionSheetItem *item = [[AHKActionSheetItem alloc] init];
  264. item.title = title;
  265. item.image = image;
  266. item.backgroundColor = backgroundColor;
  267. item.height = height;
  268. item.type = type;
  269. item.handler = handler;
  270. [self.items addObject:item];
  271. }
  272. - (void)show
  273. {
  274. if ([self isVisible]) {
  275. return;
  276. }
  277. self.previousKeyWindow = [UIApplication sharedApplication].keyWindow;
  278. UIImage *previousKeyWindowSnapshot = [self.previousKeyWindow ahk_snapshot];
  279. [self setUpNewWindow];
  280. [self setUpBlurredBackgroundWithSnapshot:previousKeyWindowSnapshot];
  281. [self setUpCancelButton];
  282. [self setUpTableView];
  283. if (self.cancelOnTapEmptyAreaEnabled.boolValue) {
  284. [self setUpCancelTapGestureForView:self.tableView];
  285. }
  286. CGFloat slideDownMinOffset = (CGFloat)fmin(CGRectGetHeight(self.frame) + self.tableView.contentOffset.y, CGRectGetHeight(self.frame));
  287. self.tableView.transform = CGAffineTransformMakeTranslation(0, slideDownMinOffset);
  288. void(^immediateAnimations)(void) = ^(void) {
  289. self.blurredBackgroundView.alpha = 1.0f;
  290. };
  291. void(^delayedAnimations)(void) = ^(void) {
  292. CGFloat width = CGRectGetWidth(self.bounds);
  293. if (width > maxWidth) width = maxWidth;
  294. self.cancelButton.frame = CGRectMake(10 + (CGRectGetWidth(self.bounds)/2 - width/2), CGRectGetMaxY(self.bounds) - self.cancelButtonHeight, width - 20, self.cancelButtonHeight - kSpaceDivide);
  295. // Corner Radius
  296. self.cancelButton.layer.cornerRadius = 10;
  297. self.cancelButton.clipsToBounds = YES;
  298. // Add White color background
  299. self.cancelButton.backgroundColor = [UIColor whiteColor];
  300. self.tableView.transform = CGAffineTransformMakeTranslation(0, 0);
  301. // manual calculation of table's contentSize.height
  302. CGFloat tableContentHeight = 0;
  303. for (AHKActionSheetItem *item in self.items) {
  304. tableContentHeight = tableContentHeight + item.height;
  305. }
  306. tableContentHeight = tableContentHeight + self.separatorHeight + CGRectGetHeight(self.tableView.tableHeaderView.frame);
  307. CGFloat topInset;
  308. BOOL buttonsFitInWithoutScrolling = tableContentHeight < CGRectGetHeight(self.tableView.frame) * (1.0 - kTopSpaceMarginFraction);
  309. if (buttonsFitInWithoutScrolling) {
  310. // show all buttons if there isn't many
  311. topInset = CGRectGetHeight(self.tableView.frame) - tableContentHeight;
  312. } else {
  313. // leave an empty space on the top to make the control look similar to UIActionSheet
  314. topInset = (CGFloat)round(CGRectGetHeight(self.tableView.frame) * kTopSpaceMarginFraction);
  315. }
  316. self.tableView.contentInset = UIEdgeInsetsMake(topInset, 0, 0, 0);
  317. self.tableView.bounces = [self.cancelOnPanGestureEnabled boolValue] || !buttonsFitInWithoutScrolling;
  318. };
  319. if ([UIView respondsToSelector:@selector(animateKeyframesWithDuration:delay:options:animations:completion:)]){
  320. // Animate sliding in tableView and cancel button with keyframe animation for a nicer effect.
  321. [UIView animateKeyframesWithDuration:self.animationDuration delay:0 options:0 animations:^{
  322. immediateAnimations();
  323. [UIView addKeyframeWithRelativeStartTime:0.3f relativeDuration:0.7f animations:^{
  324. delayedAnimations();
  325. }];
  326. } completion:nil];
  327. } else {
  328. [UIView animateWithDuration:self.animationDuration animations:^{
  329. immediateAnimations();
  330. delayedAnimations();
  331. }];
  332. }
  333. }
  334. - (void)dismissAnimated:(BOOL)animated
  335. {
  336. [self dismissAnimated:animated duration:self.animationDuration completion:self.cancelHandler];
  337. }
  338. #pragma mark - Private
  339. - (BOOL)isVisible
  340. {
  341. // action sheet is visible iff it's associated with a window
  342. return !!self.window;
  343. }
  344. - (void)dismissAnimated:(BOOL)animated duration:(NSTimeInterval)duration completion:(AHKActionSheetHandler)completionHandler
  345. {
  346. if (![self isVisible]) {
  347. return;
  348. }
  349. // delegate isn't needed anymore because tableView will be hidden (and we don't want delegate methods to be called now)
  350. self.tableView.delegate = nil;
  351. self.tableView.userInteractionEnabled = NO;
  352. // keep the table from scrolling back up
  353. self.tableView.contentInset = UIEdgeInsetsMake(-self.tableView.contentOffset.y, 0, 0, 0);
  354. void(^tearDownView)(void) = ^(void) {
  355. // remove the views because it's easiest to just recreate them if the action sheet is shown again
  356. for (UIView *view in @[self.tableView, self.cancelButton, self.blurredBackgroundView, self.window]) {
  357. [view removeFromSuperview];
  358. }
  359. self.window = nil;
  360. [self.previousKeyWindow makeKeyAndVisible];
  361. if (completionHandler) {
  362. completionHandler(self);
  363. }
  364. };
  365. if (animated) {
  366. // animate sliding down tableView and cancelButton.
  367. [UIView animateWithDuration:duration animations:^{
  368. self.blurredBackgroundView.alpha = 0.0f;
  369. self.cancelButton.transform = CGAffineTransformTranslate(self.cancelButton.transform, 0, self.cancelButtonHeight - kSpaceDivide);
  370. self.cancelButtonShadowView.alpha = 0.0f;
  371. // Shortest shift of position sufficient to hide all tableView contents below the bottom margin.
  372. // contentInset isn't used here (unlike in -show) because it caused weird problems with animations in some cases.
  373. CGFloat slideDownMinOffset = (CGFloat)fmin(CGRectGetHeight(self.frame) + self.tableView.contentOffset.y, CGRectGetHeight(self.frame));
  374. self.tableView.transform = CGAffineTransformMakeTranslation(0, slideDownMinOffset);
  375. } completion:^(BOOL finished) {
  376. tearDownView();
  377. }];
  378. } else {
  379. tearDownView();
  380. }
  381. }
  382. - (void)setUpNewWindow
  383. {
  384. AHKActionSheetViewController *actionSheetVC = [[AHKActionSheetViewController alloc] initWithNibName:nil bundle:nil];
  385. actionSheetVC.actionSheet = self;
  386. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  387. self.window.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  388. self.window.opaque = NO;
  389. self.window.rootViewController = actionSheetVC;
  390. [self.window makeKeyAndVisible];
  391. }
  392. - (void)setUpBlurredBackgroundWithSnapshot:(UIImage *)previousKeyWindowSnapshot
  393. {
  394. UIImage *blurredViewSnapshot = [previousKeyWindowSnapshot
  395. ahk_applyBlurWithRadius:self.blurRadius
  396. tintColor:self.blurTintColor
  397. saturationDeltaFactor:self.blurSaturationDeltaFactor
  398. maskImage:nil];
  399. UIImageView *backgroundView = [[UIImageView alloc] initWithImage:blurredViewSnapshot];
  400. backgroundView.frame = self.bounds;
  401. backgroundView.alpha = 0.0f;
  402. [self addSubview:backgroundView];
  403. self.blurredBackgroundView = backgroundView;
  404. }
  405. - (void)setUpCancelTapGestureForView:(UIView*)view {
  406. UITapGestureRecognizer *cancelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelButtonTapped:)];
  407. cancelTap.delegate = self;
  408. [view addGestureRecognizer:cancelTap];
  409. }
  410. - (void)setUpCancelButton
  411. {
  412. UIButton *cancelButton;
  413. CGFloat width = CGRectGetWidth(self.bounds);
  414. if (width > maxWidth) width = maxWidth;
  415. // It's hard to check if UIButtonTypeSystem enumeration exists, so we're checking existence of another method that was introduced in iOS 7.
  416. if ([UIView instancesRespondToSelector:@selector(tintAdjustmentMode)]) {
  417. cancelButton= [UIButton buttonWithType:UIButtonTypeSystem];
  418. } else {
  419. cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
  420. }
  421. NSAttributedString *attrTitle = [[NSAttributedString alloc] initWithString:self.cancelButtonTitle attributes:self.cancelButtonTextAttributes];
  422. [cancelButton setAttributedTitle:attrTitle forState:UIControlStateNormal];
  423. [cancelButton addTarget:self action:@selector(cancelButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  424. cancelButton.frame = CGRectMake(10 + (CGRectGetWidth(self.bounds)/2 - width/2), CGRectGetMaxY(self.bounds) - self.cancelButtonHeight, width - 20, self.cancelButtonHeight - kSpaceDivide);
  425. // move the button below the screen (ready to be animated -show)
  426. cancelButton.transform = CGAffineTransformMakeTranslation(0, self.cancelButtonHeight - kSpaceDivide);
  427. cancelButton.clipsToBounds = YES;
  428. [self addSubview:cancelButton];
  429. self.cancelButton = cancelButton;
  430. }
  431. - (void)setUpTableView
  432. {
  433. CGFloat width = CGRectGetWidth(self.bounds);
  434. if (width > maxWidth) width = maxWidth;
  435. CGRect statusBarViewRect = [self convertRect:[UIApplication sharedApplication].statusBarFrame fromView:nil];
  436. CGFloat statusBarHeight = CGRectGetHeight(statusBarViewRect);
  437. CGRect frame = CGRectMake((CGRectGetWidth(self.bounds)/2 - width/2), statusBarHeight, width, CGRectGetHeight(self.bounds) - statusBarHeight - self.cancelButtonHeight - self.separatorHeight);
  438. UITableView *tableView = [[UITableView alloc] initWithFrame:frame];
  439. tableView.backgroundColor = [UIColor clearColor];
  440. tableView.showsVerticalScrollIndicator = NO;
  441. tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  442. if (self.separatorColor) {
  443. tableView.separatorColor = self.separatorColor;
  444. }
  445. tableView.delegate = self;
  446. tableView.dataSource = self;
  447. [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellIdentifier];
  448. [self insertSubview:tableView aboveSubview:self.blurredBackgroundView];
  449. // move the content below the screen, ready to be animated in -show
  450. tableView.contentInset = UIEdgeInsetsMake(CGRectGetHeight(self.bounds), 0, 0, 0);
  451. // removes separators below the footer (between empty cells)
  452. tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
  453. self.tableView = tableView;
  454. }
  455. - (void)fadeBlursOnScrollToTop
  456. {
  457. if (self.tableView.isDragging || self.tableView.isDecelerating) {
  458. CGFloat alphaWithoutBounds = 1.0f - ( -(self.tableView.contentInset.top + self.tableView.contentOffset.y) / kBlurFadeRangeSize);
  459. // limit alpha to the interval [0, 1]
  460. CGFloat alpha = (CGFloat)fmax(fmin(alphaWithoutBounds, 1.0f), 0.0f);
  461. self.blurredBackgroundView.alpha = alpha;
  462. self.cancelButtonShadowView.alpha = alpha;
  463. }
  464. }
  465. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
  466. // If the view that is touched is not the view associated with this view's table view, but
  467. // is one of the sub-views, we should not recognize the touch.
  468. // Original source: http://stackoverflow.com/questions/10755566/how-to-know-uitableview-is-pressed-when-empty
  469. if (touch.view != self.tableView && [touch.view isDescendantOfView:self.tableView]) {
  470. return NO;
  471. }
  472. return YES;
  473. }
  474. @end