MWPhotoBrowser.m 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  1. //
  2. // MWPhotoBrowser.m
  3. // MWPhotoBrowser
  4. //
  5. // Created by Michael Waterfall on 14/10/2010.
  6. // Copyright 2010 d3i. All rights reserved.
  7. //
  8. #import <QuartzCore/QuartzCore.h>
  9. #import "MWCommon.h"
  10. #import "MWPhotoBrowser.h"
  11. #import "MWPhotoBrowserPrivate.h"
  12. #import "UIImage+MWPhotoBrowser.h"
  13. #import "NCBridgeSwift.h"
  14. #define PADDING 10
  15. static void * MWVideoPlayerObservation = &MWVideoPlayerObservation;
  16. @implementation MWPhotoBrowser
  17. #pragma mark - Init
  18. - (id)init {
  19. if ((self = [super init])) {
  20. [self _initialisation];
  21. }
  22. return self;
  23. }
  24. - (id)initWithDelegate:(id <MWPhotoBrowserDelegate>)delegate {
  25. if ((self = [self init])) {
  26. _delegate = delegate;
  27. }
  28. return self;
  29. }
  30. - (id)initWithPhotos:(NSArray *)photosArray {
  31. if ((self = [self init])) {
  32. _fixedPhotosArray = photosArray;
  33. }
  34. return self;
  35. }
  36. - (id)initWithCoder:(NSCoder *)decoder {
  37. if ((self = [super initWithCoder:decoder])) {
  38. [self _initialisation];
  39. }
  40. return self;
  41. }
  42. - (void)_initialisation {
  43. // Defaults
  44. NSNumber *isVCBasedStatusBarAppearanceNum = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"];
  45. if (isVCBasedStatusBarAppearanceNum) {
  46. _isVCBasedStatusBarAppearance = isVCBasedStatusBarAppearanceNum.boolValue;
  47. } else {
  48. _isVCBasedStatusBarAppearance = YES; // default
  49. }
  50. self.hidesBottomBarWhenPushed = YES;
  51. _hasBelongedToViewController = NO;
  52. _photoCount = NSNotFound;
  53. _previousLayoutBounds = CGRectZero;
  54. _currentPageIndex = 0;
  55. _previousPageIndex = NSUIntegerMax;
  56. _displayActionButton = YES;
  57. _displayShareButton = YES;
  58. _displayDeleteButton = YES;
  59. _displayNavArrows = NO;
  60. _zoomPhotosToFill = YES;
  61. _performingLayout = NO; // Reset on view did appear
  62. _rotating = NO;
  63. _viewIsActive = NO;
  64. _enableSwipeToDismiss = YES;
  65. _delayToHideElements = 5;
  66. _visiblePages = [[NSMutableSet alloc] init];
  67. _recycledPages = [[NSMutableSet alloc] init];
  68. _photos = [[NSMutableArray alloc] init];
  69. _thumbPhotos = [[NSMutableArray alloc] init];
  70. _didSavePreviousStateOfNavBar = NO;
  71. self.automaticallyAdjustsScrollViewInsets = NO;
  72. // Listen for MWPhoto notifications
  73. [[NSNotificationCenter defaultCenter] addObserver:self
  74. selector:@selector(handleMWPhotoLoadingDidEndNotification:)
  75. name:MWPHOTO_LOADING_DID_END_NOTIFICATION
  76. object:nil];
  77. }
  78. - (void)dealloc {
  79. [self clearCurrentVideo];
  80. _pagingScrollView.delegate = nil;
  81. [[NSNotificationCenter defaultCenter] removeObserver:self];
  82. [self releaseAllUnderlyingPhotos:NO];
  83. }
  84. - (void)releaseAllUnderlyingPhotos:(BOOL)preserveCurrent {
  85. // Create a copy in case this array is modified while we are looping through
  86. // Release photos
  87. NSArray *copy = [_photos copy];
  88. for (id p in copy) {
  89. if (p != [NSNull null]) {
  90. if (preserveCurrent && p == [self photoAtIndex:self.currentIndex]) {
  91. continue; // skip current
  92. }
  93. [p unloadUnderlyingImage];
  94. }
  95. }
  96. // Release thumbs
  97. copy = [_thumbPhotos copy];
  98. for (id p in copy) {
  99. if (p != [NSNull null]) {
  100. [p unloadUnderlyingImage];
  101. }
  102. }
  103. }
  104. - (void)didReceiveMemoryWarning {
  105. // Release any cached data, images, etc that aren't in use.
  106. [self releaseAllUnderlyingPhotos:YES];
  107. [_recycledPages removeAllObjects];
  108. // Releases the view if it doesn't have a superview.
  109. [super didReceiveMemoryWarning];
  110. }
  111. #pragma mark - View Loading
  112. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  113. - (void)viewDidLoad {
  114. // View
  115. self.view.backgroundColor = [UIColor whiteColor];
  116. self.view.clipsToBounds = YES;
  117. // Setup paging scrolling view
  118. CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
  119. _pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame];
  120. _pagingScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  121. _pagingScrollView.pagingEnabled = YES;
  122. _pagingScrollView.delegate = self;
  123. _pagingScrollView.showsHorizontalScrollIndicator = NO;
  124. _pagingScrollView.showsVerticalScrollIndicator = NO;
  125. _pagingScrollView.backgroundColor = [UIColor whiteColor];
  126. _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
  127. [self.view addSubview:_pagingScrollView];
  128. // Toolbar
  129. _toolbar = [[UIToolbar alloc] initWithFrame:[self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]]];
  130. _toolbar.tintColor = [NCBrandColor sharedInstance].brand;
  131. _toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  132. [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  133. [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsCompact];
  134. _toolbar.barStyle = UIBarStyleDefault; //TWS
  135. _toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
  136. [_toolbar setTranslucent:NO];
  137. // Toolbar Items
  138. if (self.displayNavArrows) {
  139. NSString *arrowPathFormat = @"UIBarButtonItemArrow%@";
  140. UIImage *previousButtonImage = [UIImage imageForResourcePath:[NSString stringWithFormat:arrowPathFormat, @"Left"] ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  141. UIImage *nextButtonImage = [UIImage imageForResourcePath:[NSString stringWithFormat:arrowPathFormat, @"Right"] ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  142. _previousButton = [[UIBarButtonItem alloc] initWithImage:previousButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(gotoPreviousPage)];
  143. _nextButton = [[UIBarButtonItem alloc] initWithImage:nextButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextPage)];
  144. }
  145. //TWS
  146. if (self.displayDeleteButton) {
  147. _deleteButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteButtonPressed:)];
  148. }
  149. if (self.displayActionButton) {
  150. _actionButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionButtonPressed:)];
  151. }
  152. if (self.displayShareButton) {
  153. _shareButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"actionSheetShare"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonPressed:)];
  154. }
  155. // Update
  156. [self reloadData];
  157. // Swipe to dismiss
  158. if (_enableSwipeToDismiss) {
  159. UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doneButtonPressed:)];
  160. swipeGesture.direction = UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp;
  161. [self.view addGestureRecognizer:swipeGesture];
  162. }
  163. // Super
  164. [super viewDidLoad];
  165. }
  166. - (void)performLayout {
  167. // Setup
  168. _performingLayout = YES;
  169. NSUInteger numberOfPhotos = [self numberOfPhotos];
  170. // Setup pages
  171. [_visiblePages removeAllObjects];
  172. [_recycledPages removeAllObjects];
  173. // Navigation buttons
  174. if ([self.navigationController.viewControllers objectAtIndex:0] == self) {
  175. // We're first on stack so show done button
  176. _doneButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", nil) style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed:)];
  177. // Set appearance
  178. [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  179. [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsCompact];
  180. [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  181. [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsCompact];
  182. [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
  183. [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
  184. self.navigationItem.rightBarButtonItem = _doneButton;
  185. }
  186. // color
  187. self.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  188. self.navigationController.navigationBar.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  189. [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].navigationBarText}];
  190. // Toolbar items
  191. BOOL hasItems = NO;
  192. UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  193. fixedSpace.width = 32; // To balance action button
  194. UIBarButtonItem *fixedSpaceMini = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  195. fixedSpaceMini.width = 25; // To balance action button
  196. UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
  197. NSMutableArray *items = [[NSMutableArray alloc] init];
  198. // Middle - Nav
  199. if (_previousButton && _nextButton && numberOfPhotos > 1) {
  200. hasItems = YES;
  201. [items addObject:_previousButton];
  202. [items addObject:fixedSpace];
  203. [items addObject:fixedSpace];
  204. [items addObject:_nextButton];
  205. [items addObject:flexSpace];
  206. } else {
  207. [items addObject:flexSpace];
  208. }
  209. // Right - Action
  210. if (_actionButton) {
  211. if (_deleteButton) {
  212. [items addObject:_deleteButton];
  213. [items addObject:fixedSpaceMini];
  214. }
  215. if (_shareButton) {
  216. [items addObject:_shareButton];
  217. [items addObject:fixedSpaceMini];
  218. }
  219. [items addObject:_actionButton];
  220. } else {
  221. // We're not showing the toolbar so try and show in top right
  222. if (_actionButton)
  223. self.navigationItem.rightBarButtonItem = _actionButton;
  224. [items addObject:fixedSpace];
  225. }
  226. // Toolbar visibility
  227. [_toolbar setItems:items];
  228. BOOL hideToolbar = YES;
  229. for (UIBarButtonItem* item in _toolbar.items) {
  230. if (item != fixedSpace && item != flexSpace) {
  231. hideToolbar = NO;
  232. break;
  233. }
  234. }
  235. if (hideToolbar) {
  236. [_toolbar removeFromSuperview];
  237. } else {
  238. [self.view addSubview:_toolbar];
  239. }
  240. // Update nav
  241. [self updateNavigation];
  242. // Content offset
  243. _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:_currentPageIndex];
  244. [self tilePages];
  245. _performingLayout = NO;
  246. }
  247. // Release any retained subviews of the main view.
  248. - (void)viewDidUnload {
  249. _currentPageIndex = 0;
  250. _pagingScrollView = nil;
  251. _visiblePages = nil;
  252. _recycledPages = nil;
  253. _toolbar = nil;
  254. _previousButton = nil;
  255. _nextButton = nil;
  256. _progressHUD = nil;
  257. [super viewDidUnload];
  258. }
  259. - (BOOL)presentingViewControllerPrefersStatusBarHidden {
  260. UIViewController *presenting = self.presentingViewController;
  261. if (presenting) {
  262. if ([presenting isKindOfClass:[UINavigationController class]]) {
  263. presenting = [(UINavigationController *)presenting topViewController];
  264. }
  265. } else {
  266. // We're in a navigation controller so get previous one!
  267. if (self.navigationController && self.navigationController.viewControllers.count > 1) {
  268. presenting = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2];
  269. }
  270. }
  271. if (presenting) {
  272. return [presenting prefersStatusBarHidden];
  273. } else {
  274. return NO;
  275. }
  276. }
  277. #pragma mark - Appearance
  278. - (void)viewWillAppear:(BOOL)animated {
  279. // Super
  280. [super viewWillAppear:animated];
  281. // Status bar
  282. if (!_viewHasAppearedInitially) {
  283. _leaveStatusBarAlone = [self presentingViewControllerPrefersStatusBarHidden];
  284. // Check if status bar is hidden on first appear, and if so then ignore it
  285. if (CGRectEqualToRect([[UIApplication sharedApplication] statusBarFrame], CGRectZero)) {
  286. _leaveStatusBarAlone = YES;
  287. }
  288. }
  289. // Nav Bar Appearance iPAD
  290. if (self.traitCollection.horizontalSizeClass != UIUserInterfaceSizeClassCompact) {
  291. // ----- TWS ----- //
  292. self.navigationItem.hidesBackButton = YES;
  293. self.navigationController.topViewController.navigationItem.leftBarButtonItem = self.splitViewController.displayModeButtonItem;
  294. self.splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  295. }
  296. // Update UI
  297. [self hideControlsAfterDelay];
  298. // If rotation occured while we're presenting a modal
  299. // and the index changed, make sure we show the right one now
  300. if (_currentPageIndex != _pageIndexBeforeRotation) {
  301. [self jumpToPageAtIndex:_pageIndexBeforeRotation animated:NO];
  302. }
  303. // Layaout
  304. [self.view setNeedsLayout];
  305. }
  306. - (void)viewDidAppear:(BOOL)animated {
  307. [super viewDidAppear:animated];
  308. _viewIsActive = YES;
  309. // Autoplay if first is video
  310. if (!_viewHasAppearedInitially) {
  311. if (_autoPlayOnAppear) {
  312. MWPhoto *photo = [self photoAtIndex:_currentPageIndex];
  313. if ([photo respondsToSelector:@selector(isVideo)] && photo.isVideo) {
  314. [self playVideoAtIndex:_currentPageIndex];
  315. }
  316. }
  317. }
  318. _viewHasAppearedInitially = YES;
  319. }
  320. - (void)viewWillDisappear:(BOOL)animated {
  321. // Detect if rotation occurs while we're presenting a modal
  322. _pageIndexBeforeRotation = _currentPageIndex;
  323. // Check that we're being popped for good
  324. if ([self.navigationController.viewControllers objectAtIndex:0] != self &&
  325. ![self.navigationController.viewControllers containsObject:self]) {
  326. // State
  327. _viewIsActive = NO;
  328. [self clearCurrentVideo]; // Clear current playing video
  329. }
  330. // Controls
  331. [self.navigationController.navigationBar.layer removeAllAnimations]; // Stop all animations on nav bar
  332. [NSObject cancelPreviousPerformRequestsWithTarget:self]; // Cancel any pending toggles from taps
  333. [self setControlsHidden:NO animated:NO permanent:YES];
  334. // Super
  335. [super viewWillDisappear:animated];
  336. }
  337. - (void)willMoveToParentViewController:(UIViewController *)parent {
  338. if (parent && _hasBelongedToViewController) {
  339. [NSException raise:@"MWPhotoBrowser Instance Reuse" format:@"MWPhotoBrowser instances cannot be reused."];
  340. }
  341. }
  342. - (void)didMoveToParentViewController:(UIViewController *)parent {
  343. if (!parent) _hasBelongedToViewController = YES;
  344. }
  345. #pragma mark - Layout
  346. - (void)viewWillLayoutSubviews {
  347. [super viewWillLayoutSubviews];
  348. [self layoutVisiblePages];
  349. }
  350. - (void)layoutVisiblePages {
  351. // Flag
  352. _performingLayout = YES;
  353. // Toolbar
  354. _toolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  355. // Remember index
  356. NSUInteger indexPriorToLayout = _currentPageIndex;
  357. // Get paging scroll view frame to determine if anything needs changing
  358. CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
  359. // Frame needs changing
  360. if (!_skipNextPagingScrollViewPositioning) {
  361. _pagingScrollView.frame = pagingScrollViewFrame;
  362. }
  363. _skipNextPagingScrollViewPositioning = NO;
  364. // Recalculate contentSize based on current orientation
  365. _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
  366. // Adjust frames and configuration of each visible page
  367. for (MWZoomingScrollView *page in _visiblePages) {
  368. NSUInteger index = page.index;
  369. page.frame = [self frameForPageAtIndex:index];
  370. if (page.captionView) {
  371. page.captionView.frame = [self frameForCaptionView:page.captionView atIndex:index];
  372. }
  373. if (page.selectedButton) {
  374. page.selectedButton.frame = [self frameForSelectedButton:page.selectedButton atIndex:index];
  375. }
  376. if (page.playButton) {
  377. page.playButton.frame = [self frameForPlayButton:page.playButton atIndex:index];
  378. }
  379. // Adjust scales if bounds has changed since last time
  380. if (!CGRectEqualToRect(_previousLayoutBounds, self.view.bounds)) {
  381. // Update zooms for new bounds
  382. [page setMaxMinZoomScalesForCurrentBounds];
  383. _previousLayoutBounds = self.view.bounds;
  384. }
  385. }
  386. // Adjust video loading indicator if it's visible
  387. [self positionVideoLoadingIndicator];
  388. // Adjust contentOffset to preserve page location based on values collected prior to location
  389. _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:indexPriorToLayout];
  390. [self didStartViewingPageAtIndex:_currentPageIndex]; // initial
  391. // Reset
  392. _currentPageIndex = indexPriorToLayout;
  393. _performingLayout = NO;
  394. }
  395. #pragma mark - Rotation
  396. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
  397. return YES;
  398. }
  399. #if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
  400. - (NSUInteger)supportedInterfaceOrientations
  401. #else
  402. - (UIInterfaceOrientationMask)supportedInterfaceOrientations
  403. #endif
  404. {
  405. return UIInterfaceOrientationMaskPortrait;
  406. }
  407. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  408. // Remember page index before rotation
  409. _pageIndexBeforeRotation = _currentPageIndex;
  410. _rotating = YES;
  411. // In iOS 7 the nav bar gets shown after rotation, but might as well do this for everything!
  412. if ([self areControlsHidden]) {
  413. // Force hidden
  414. self.navigationController.navigationBarHidden = YES;
  415. }
  416. }
  417. - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  418. // Perform layout
  419. _currentPageIndex = _pageIndexBeforeRotation;
  420. // Delay control holding
  421. [self hideControlsAfterDelay];
  422. // Layout
  423. [self layoutVisiblePages];
  424. }
  425. - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
  426. _rotating = NO;
  427. // Ensure nav bar isn't re-displayed
  428. if ([self areControlsHidden]) {
  429. self.navigationController.navigationBarHidden = NO;
  430. self.navigationController.navigationBar.alpha = 0;
  431. }
  432. }
  433. #pragma mark - Data
  434. - (NSUInteger)currentIndex {
  435. return _currentPageIndex;
  436. }
  437. - (void)reloadData {
  438. // Reset
  439. _photoCount = NSNotFound;
  440. // Get data
  441. NSUInteger numberOfPhotos = [self numberOfPhotos];
  442. [self releaseAllUnderlyingPhotos:YES];
  443. [_photos removeAllObjects];
  444. [_thumbPhotos removeAllObjects];
  445. for (int i = 0; i < numberOfPhotos; i++) {
  446. [_photos addObject:[NSNull null]];
  447. [_thumbPhotos addObject:[NSNull null]];
  448. }
  449. // Update current page index
  450. if (numberOfPhotos > 0) {
  451. _currentPageIndex = MAX(0, MIN(_currentPageIndex, numberOfPhotos - 1));
  452. } else {
  453. _currentPageIndex = 0;
  454. }
  455. // Update layout
  456. if ([self isViewLoaded]) {
  457. while (_pagingScrollView.subviews.count) {
  458. [[_pagingScrollView.subviews lastObject] removeFromSuperview];
  459. }
  460. [self performLayout];
  461. [self.view setNeedsLayout];
  462. }
  463. //_toolbar.hidden = (_gridController ? true : false);
  464. //_toolbar.alpha = (_gridController ? 0 : 1);
  465. //TWS
  466. //self.navigationController.navigationBar.hidden = (_gridController ? true : false);
  467. // self.navigationController.navigationBar.alpha = (_gridController ? 0 : 1);
  468. }
  469. - (NSUInteger)numberOfPhotos {
  470. if (_photoCount == NSNotFound) {
  471. if ([_delegate respondsToSelector:@selector(numberOfPhotosInPhotoBrowser:)]) {
  472. _photoCount = [_delegate numberOfPhotosInPhotoBrowser:self];
  473. } else if (_fixedPhotosArray) {
  474. _photoCount = _fixedPhotosArray.count;
  475. }
  476. }
  477. if (_photoCount == NSNotFound) _photoCount = 0;
  478. return _photoCount;
  479. }
  480. - (id<MWPhoto>)photoAtIndex:(NSUInteger)index {
  481. id <MWPhoto> photo = nil;
  482. if (index < _photos.count) {
  483. if ([_photos objectAtIndex:index] == [NSNull null]) {
  484. if ([_delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:)]) {
  485. photo = [_delegate photoBrowser:self photoAtIndex:index];
  486. } else if (_fixedPhotosArray && index < _fixedPhotosArray.count) {
  487. photo = [_fixedPhotosArray objectAtIndex:index];
  488. }
  489. if (photo) [_photos replaceObjectAtIndex:index withObject:photo];
  490. } else {
  491. photo = [_photos objectAtIndex:index];
  492. }
  493. }
  494. return photo;
  495. }
  496. - (id<MWPhoto>)thumbPhotoAtIndex:(NSUInteger)index {
  497. id <MWPhoto> photo = nil;
  498. if (index < _thumbPhotos.count) {
  499. if ([_thumbPhotos objectAtIndex:index] == [NSNull null]) {
  500. if ([_delegate respondsToSelector:@selector(photoBrowser:thumbPhotoAtIndex:)]) {
  501. photo = [_delegate photoBrowser:self thumbPhotoAtIndex:index];
  502. }
  503. if (photo) [_thumbPhotos replaceObjectAtIndex:index withObject:photo];
  504. } else {
  505. photo = [_thumbPhotos objectAtIndex:index];
  506. }
  507. }
  508. return photo;
  509. }
  510. - (MWCaptionView *)captionViewForPhotoAtIndex:(NSUInteger)index {
  511. MWCaptionView *captionView = nil;
  512. if ([_delegate respondsToSelector:@selector(photoBrowser:captionViewForPhotoAtIndex:)]) {
  513. captionView = [_delegate photoBrowser:self captionViewForPhotoAtIndex:index];
  514. } else {
  515. id <MWPhoto> photo = [self photoAtIndex:index];
  516. if ([photo respondsToSelector:@selector(caption)]) {
  517. if ([photo caption]) captionView = [[MWCaptionView alloc] initWithPhoto:photo];
  518. }
  519. }
  520. captionView.alpha = [self areControlsHidden] ? 0 : 1; // Initial alpha
  521. return captionView;
  522. }
  523. - (BOOL)photoIsSelectedAtIndex:(NSUInteger)index {
  524. BOOL value = NO;
  525. if (_displaySelectionButtons) {
  526. if ([self.delegate respondsToSelector:@selector(photoBrowser:isPhotoSelectedAtIndex:)]) {
  527. value = [self.delegate photoBrowser:self isPhotoSelectedAtIndex:index];
  528. }
  529. }
  530. return value;
  531. }
  532. - (void)setPhotoSelected:(BOOL)selected atIndex:(NSUInteger)index {
  533. if (_displaySelectionButtons) {
  534. if ([self.delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:selectedChanged:)]) {
  535. [self.delegate photoBrowser:self photoAtIndex:index selectedChanged:selected];
  536. }
  537. }
  538. }
  539. - (UIImage *)imageForPhoto:(id<MWPhoto>)photo {
  540. if (photo) {
  541. // Get image or obtain in background
  542. if ([photo underlyingImage]) {
  543. return [photo underlyingImage];
  544. } else {
  545. [photo loadUnderlyingImageAndNotify];
  546. }
  547. }
  548. return nil;
  549. }
  550. - (void)loadAdjacentPhotosIfNecessary:(id<MWPhoto>)photo
  551. {
  552. MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
  553. if (page) {
  554. // If page is current page then initiate loading of previous and next pages
  555. NSUInteger pageIndex = page.index;
  556. if (_currentPageIndex == pageIndex) {
  557. if (pageIndex > 0) {
  558. // Preload index - 1
  559. id <MWPhoto> photo = [self photoAtIndex:pageIndex-1];
  560. if (![photo underlyingImage]) {
  561. [photo loadUnderlyingImageAndNotify];
  562. MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex-1);
  563. }
  564. }
  565. if (pageIndex < [self numberOfPhotos] - 1) {
  566. // Preload index + 1
  567. id <MWPhoto> photo = [self photoAtIndex:pageIndex+1];
  568. if (![photo underlyingImage]) {
  569. [photo loadUnderlyingImageAndNotify];
  570. MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex+1);
  571. }
  572. }
  573. }
  574. }
  575. }
  576. #pragma mark - MWPhoto Loading Notification
  577. - (void)handleMWPhotoLoadingDidEndNotification:(NSNotification *)notification {
  578. id <MWPhoto> photo = [notification object];
  579. MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
  580. if (page) {
  581. if ([photo underlyingImage]) {
  582. // Successful load
  583. [page displayImage];
  584. [self loadAdjacentPhotosIfNecessary:photo];
  585. } else {
  586. // Failed to load
  587. [page displayImageFailure];
  588. }
  589. // Update nav
  590. [self updateNavigation];
  591. }
  592. }
  593. #pragma mark - Paging
  594. - (void)tilePages {
  595. // Calculate which pages should be visible
  596. // Ignore padding as paging bounces encroach on that
  597. // and lead to false page loads
  598. CGRect visibleBounds = _pagingScrollView.bounds;
  599. NSInteger iFirstIndex = (NSInteger)floorf((CGRectGetMinX(visibleBounds)+PADDING*2) / CGRectGetWidth(visibleBounds));
  600. NSInteger iLastIndex = (NSInteger)floorf((CGRectGetMaxX(visibleBounds)-PADDING*2-1) / CGRectGetWidth(visibleBounds));
  601. if (iFirstIndex < 0) iFirstIndex = 0;
  602. if (iFirstIndex > [self numberOfPhotos] - 1) iFirstIndex = [self numberOfPhotos] - 1;
  603. if (iLastIndex < 0) iLastIndex = 0;
  604. if (iLastIndex > [self numberOfPhotos] - 1) iLastIndex = [self numberOfPhotos] - 1;
  605. // Recycle no longer needed pages
  606. NSInteger pageIndex;
  607. for (MWZoomingScrollView *page in _visiblePages) {
  608. pageIndex = page.index;
  609. if (pageIndex < (NSUInteger)iFirstIndex || pageIndex > (NSUInteger)iLastIndex) {
  610. [_recycledPages addObject:page];
  611. [page.captionView removeFromSuperview];
  612. [page.selectedButton removeFromSuperview];
  613. [page.playButton removeFromSuperview];
  614. [page prepareForReuse];
  615. [page removeFromSuperview];
  616. MWLog(@"Removed page at index %lu", (unsigned long)pageIndex);
  617. }
  618. }
  619. [_visiblePages minusSet:_recycledPages];
  620. while (_recycledPages.count > 2) // Only keep 2 recycled pages
  621. [_recycledPages removeObject:[_recycledPages anyObject]];
  622. // Add missing pages
  623. for (NSUInteger index = (NSUInteger)iFirstIndex; index <= (NSUInteger)iLastIndex; index++) {
  624. if (![self isDisplayingPageForIndex:index]) {
  625. // Add new page
  626. MWZoomingScrollView *page = [self dequeueRecycledPage];
  627. if (!page) {
  628. page = [[MWZoomingScrollView alloc] initWithPhotoBrowser:self];
  629. }
  630. [_visiblePages addObject:page];
  631. [self configurePage:page forIndex:index];
  632. [_pagingScrollView addSubview:page];
  633. MWLog(@"Added page at index %lu", (unsigned long)index);
  634. // Add caption
  635. MWCaptionView *captionView = [self captionViewForPhotoAtIndex:index];
  636. if (captionView) {
  637. captionView.frame = [self frameForCaptionView:captionView atIndex:index];
  638. [_pagingScrollView addSubview:captionView];
  639. page.captionView = captionView;
  640. }
  641. // Add play button if needed
  642. if (page.displayingVideo) {
  643. UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
  644. [playButton setImage:[UIImage imageForResourcePath:@"PlayButtonOverlayLarge" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateNormal];
  645. [playButton setImage:[UIImage imageForResourcePath:@"PlayButtonOverlayLargeTap" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateHighlighted];
  646. [playButton addTarget:self action:@selector(playButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  647. [playButton sizeToFit];
  648. playButton.frame = [self frameForPlayButton:playButton atIndex:index];
  649. [_pagingScrollView addSubview:playButton];
  650. page.playButton = playButton;
  651. }
  652. // Add selected button
  653. if (self.displaySelectionButtons) {
  654. UIButton *selectedButton = [UIButton buttonWithType:UIButtonTypeCustom];
  655. [selectedButton setImage:[UIImage imageForResourcePath:@"ImageSelectedOff" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateNormal];
  656. UIImage *selectedOnImage;
  657. if (self.customImageSelectedIconName) {
  658. selectedOnImage = [UIImage imageNamed:self.customImageSelectedIconName];
  659. } else {
  660. selectedOnImage = [UIImage imageForResourcePath:@"ImageSelectedOn" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  661. }
  662. [selectedButton setImage:selectedOnImage forState:UIControlStateSelected];
  663. [selectedButton sizeToFit];
  664. selectedButton.adjustsImageWhenHighlighted = NO;
  665. [selectedButton addTarget:self action:@selector(selectedButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  666. selectedButton.frame = [self frameForSelectedButton:selectedButton atIndex:index];
  667. [_pagingScrollView addSubview:selectedButton];
  668. page.selectedButton = selectedButton;
  669. selectedButton.selected = [self photoIsSelectedAtIndex:index];
  670. }
  671. }
  672. }
  673. }
  674. - (void)updateVisiblePageStates {
  675. NSSet *copy = [_visiblePages copy];
  676. for (MWZoomingScrollView *page in copy) {
  677. // Update selection
  678. page.selectedButton.selected = [self photoIsSelectedAtIndex:page.index];
  679. }
  680. }
  681. - (BOOL)isDisplayingPageForIndex:(NSUInteger)index {
  682. for (MWZoomingScrollView *page in _visiblePages)
  683. if (page.index == index) return YES;
  684. return NO;
  685. }
  686. - (MWZoomingScrollView *)pageDisplayedAtIndex:(NSUInteger)index {
  687. MWZoomingScrollView *thePage = nil;
  688. for (MWZoomingScrollView *page in _visiblePages) {
  689. if (page.index == index) {
  690. thePage = page; break;
  691. }
  692. }
  693. return thePage;
  694. }
  695. - (MWZoomingScrollView *)pageDisplayingPhoto:(id<MWPhoto>)photo {
  696. MWZoomingScrollView *thePage = nil;
  697. for (MWZoomingScrollView *page in _visiblePages) {
  698. if (page.photo == photo) {
  699. thePage = page; break;
  700. }
  701. }
  702. return thePage;
  703. }
  704. - (void)configurePage:(MWZoomingScrollView *)page forIndex:(NSUInteger)index {
  705. page.frame = [self frameForPageAtIndex:index];
  706. page.index = index;
  707. page.photo = [self photoAtIndex:index];
  708. }
  709. - (MWZoomingScrollView *)dequeueRecycledPage {
  710. MWZoomingScrollView *page = [_recycledPages anyObject];
  711. if (page) {
  712. [_recycledPages removeObject:page];
  713. }
  714. return page;
  715. }
  716. // Handle page changes
  717. - (void)didStartViewingPageAtIndex:(NSUInteger)index {
  718. // Handle 0 photos
  719. if (![self numberOfPhotos]) {
  720. // Show controls
  721. [self setControlsHidden:NO animated:YES permanent:YES];
  722. return;
  723. }
  724. // Handle video on page change
  725. if (!_rotating || index != _currentVideoIndex) {
  726. [self clearCurrentVideo];
  727. }
  728. // Release images further away than +/-1
  729. NSUInteger i;
  730. if (index > 0) {
  731. // Release anything < index - 1
  732. for (i = 0; i < index-1; i++) {
  733. id photo = [_photos objectAtIndex:i];
  734. if (photo != [NSNull null]) {
  735. [photo unloadUnderlyingImage];
  736. [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
  737. MWLog(@"Released underlying image at index %lu", (unsigned long)i);
  738. }
  739. }
  740. }
  741. if (index < [self numberOfPhotos] - 1) {
  742. // Release anything > index + 1
  743. for (i = index + 2; i < _photos.count; i++) {
  744. id photo = [_photos objectAtIndex:i];
  745. if (photo != [NSNull null]) {
  746. [photo unloadUnderlyingImage];
  747. [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
  748. MWLog(@"Released underlying image at index %lu", (unsigned long)i);
  749. }
  750. }
  751. }
  752. // Load adjacent images if needed and the photo is already
  753. // loaded. Also called after photo has been loaded in background
  754. id <MWPhoto> currentPhoto = [self photoAtIndex:index];
  755. if ([currentPhoto underlyingImage]) {
  756. // photo loaded so load ajacent now
  757. [self loadAdjacentPhotosIfNecessary:currentPhoto];
  758. }
  759. // Notify delegate
  760. if (index != _previousPageIndex) {
  761. if ([_delegate respondsToSelector:@selector(photoBrowser:didDisplayPhotoAtIndex:)])
  762. [_delegate photoBrowser:self didDisplayPhotoAtIndex:index];
  763. _previousPageIndex = index;
  764. } else {
  765. if ([_delegate respondsToSelector:@selector(photoBrowser:didDisplayPhotoAtIndex:)])
  766. [_delegate photoBrowser:self didDisplayPhotoAtIndex:index];
  767. }
  768. // Update nav
  769. [self updateNavigation];
  770. }
  771. #pragma mark - Frame Calculations
  772. - (CGRect)frameForPagingScrollView {
  773. CGRect frame = self.view.bounds;// [[UIScreen mainScreen] bounds];
  774. frame.origin.x -= PADDING;
  775. frame.size.width += (2 * PADDING);
  776. return CGRectIntegral(frame);
  777. }
  778. - (CGRect)frameForPageAtIndex:(NSUInteger)index {
  779. // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in
  780. // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's
  781. // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape
  782. // because it has a rotation transform applied.
  783. CGRect bounds = _pagingScrollView.bounds;
  784. CGRect pageFrame = bounds;
  785. pageFrame.size.width -= (2 * PADDING);
  786. pageFrame.origin.x = (bounds.size.width * index) + PADDING;
  787. return CGRectIntegral(pageFrame);
  788. }
  789. - (CGSize)contentSizeForPagingScrollView {
  790. // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
  791. CGRect bounds = _pagingScrollView.bounds;
  792. return CGSizeMake(bounds.size.width * [self numberOfPhotos], bounds.size.height);
  793. }
  794. - (CGPoint)contentOffsetForPageAtIndex:(NSUInteger)index {
  795. CGFloat pageWidth = _pagingScrollView.bounds.size.width;
  796. CGFloat newOffset = index * pageWidth;
  797. return CGPointMake(newOffset, 0);
  798. }
  799. - (CGRect)frameForToolbarAtOrientation:(UIInterfaceOrientation)orientation {
  800. CGFloat _safeAreaBottom = 0;
  801. CGFloat height = 49;
  802. // iOS 11 safeArea
  803. if (@available(iOS 11, *)) {
  804. _safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  805. }
  806. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && UIInterfaceOrientationIsLandscape(orientation))
  807. height = 39;
  808. return CGRectIntegral(CGRectMake(0, self.view.bounds.size.height - height - _safeAreaBottom, self.view.bounds.size.width, height ));
  809. }
  810. - (CGRect)frameForCaptionView:(MWCaptionView *)captionView atIndex:(NSUInteger)index {
  811. // iOS 11 safeArea
  812. CGFloat _safeAreaBottom = 0;
  813. if (@available(iOS 11, *)) {
  814. _safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  815. }
  816. CGRect pageFrame = [self frameForPageAtIndex:index];
  817. CGSize captionSize = [captionView sizeThatFits:CGSizeMake(pageFrame.size.width, 0)];
  818. CGRect captionFrame = CGRectMake(pageFrame.origin.x,
  819. pageFrame.size.height - captionSize.height - (_toolbar.superview?_toolbar.frame.size.height:0) - _safeAreaBottom,
  820. pageFrame.size.width,
  821. captionSize.height);
  822. return CGRectIntegral(captionFrame);
  823. }
  824. - (CGRect)frameForSelectedButton:(UIButton *)selectedButton atIndex:(NSUInteger)index {
  825. CGRect pageFrame = [self frameForPageAtIndex:index];
  826. CGFloat padding = 20;
  827. CGFloat yOffset = 0;
  828. if (![self areControlsHidden]) {
  829. UINavigationBar *navBar = self.navigationController.navigationBar;
  830. yOffset = navBar.frame.origin.y + navBar.frame.size.height;
  831. }
  832. CGRect selectedButtonFrame = CGRectMake(pageFrame.origin.x + pageFrame.size.width - selectedButton.frame.size.width - padding,
  833. padding + yOffset,
  834. selectedButton.frame.size.width,
  835. selectedButton.frame.size.height);
  836. return CGRectIntegral(selectedButtonFrame);
  837. }
  838. - (CGRect)frameForPlayButton:(UIButton *)playButton atIndex:(NSUInteger)index {
  839. CGRect pageFrame = [self frameForPageAtIndex:index];
  840. return CGRectMake(floorf(CGRectGetMidX(pageFrame) - playButton.frame.size.width / 2),
  841. floorf(CGRectGetMidY(pageFrame) - playButton.frame.size.height / 2),
  842. playButton.frame.size.width,
  843. playButton.frame.size.height);
  844. }
  845. #pragma mark - UIScrollView Delegate
  846. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  847. // Checks
  848. if (!_viewIsActive || _performingLayout || _rotating) return;
  849. // Tile pages
  850. [self tilePages];
  851. // Calculate current page
  852. CGRect visibleBounds = _pagingScrollView.bounds;
  853. NSInteger index = (NSInteger)(floorf(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds)));
  854. if (index < 0) index = 0;
  855. if (index > [self numberOfPhotos] - 1) index = [self numberOfPhotos] - 1;
  856. NSUInteger previousCurrentPage = _currentPageIndex;
  857. _currentPageIndex = index;
  858. if (_currentPageIndex != previousCurrentPage) {
  859. [self didStartViewingPageAtIndex:index];
  860. }
  861. }
  862. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  863. // Hide controls when dragging begins
  864. [self setControlsHidden:YES animated:YES permanent:NO];
  865. }
  866. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  867. // Update nav when page changes
  868. [self updateNavigation];
  869. }
  870. #pragma mark - Navigation
  871. - (void)updateNavigation {
  872. // Title
  873. NSUInteger numberOfPhotos = [self numberOfPhotos];
  874. if (numberOfPhotos > 1) {
  875. if ([_delegate respondsToSelector:@selector(photoBrowser:titleForPhotoAtIndex:)]) {
  876. self.title = [_delegate photoBrowser:self titleForPhotoAtIndex:_currentPageIndex];
  877. } else {
  878. self.title = [NSString stringWithFormat:@"%lu %@ %lu", (unsigned long)(_currentPageIndex+1), NSLocalizedString(@"of", @"Used in the context: 'Showing 1 of 3 items'"), (unsigned long)numberOfPhotos];
  879. }
  880. } else {
  881. self.title = nil;
  882. }
  883. // Buttons
  884. _previousButton.enabled = (_currentPageIndex > 0);
  885. _nextButton.enabled = (_currentPageIndex < numberOfPhotos - 1);
  886. //TWS Disable action button if there is no image or it's a video
  887. /*
  888. MWPhoto *photo = [self photoAtIndex:_currentPageIndex];
  889. if ([photo underlyingImage] == nil || ([photo respondsToSelector:@selector(isVideo)] && photo.isVideo)) {
  890. _actionButton.enabled = NO;
  891. _actionButton.tintColor = [UIColor clearColor]; // Tint to hide button
  892. } else {
  893. _actionButton.enabled = YES;
  894. _actionButton.tintColor = nil;
  895. }
  896. */
  897. }
  898. - (void)jumpToPageAtIndex:(NSUInteger)index animated:(BOOL)animated {
  899. // Change page
  900. if (index < [self numberOfPhotos]) {
  901. CGRect pageFrame = [self frameForPageAtIndex:index];
  902. [_pagingScrollView setContentOffset:CGPointMake(pageFrame.origin.x - PADDING, 0) animated:animated];
  903. [self updateNavigation];
  904. }
  905. // Update timer to give more time
  906. [self hideControlsAfterDelay];
  907. }
  908. - (void)gotoPreviousPage {
  909. [self showPreviousPhotoAnimated:NO];
  910. }
  911. - (void)gotoNextPage {
  912. [self showNextPhotoAnimated:NO];
  913. }
  914. - (void)showPreviousPhotoAnimated:(BOOL)animated {
  915. [self jumpToPageAtIndex:_currentPageIndex-1 animated:animated];
  916. }
  917. - (void)showNextPhotoAnimated:(BOOL)animated {
  918. [self jumpToPageAtIndex:_currentPageIndex+1 animated:animated];
  919. }
  920. #pragma mark - Interactions
  921. - (void)selectedButtonTapped:(id)sender {
  922. UIButton *selectedButton = (UIButton *)sender;
  923. selectedButton.selected = !selectedButton.selected;
  924. NSUInteger index = NSUIntegerMax;
  925. for (MWZoomingScrollView *page in _visiblePages) {
  926. if (page.selectedButton == selectedButton) {
  927. index = page.index;
  928. break;
  929. }
  930. }
  931. if (index != NSUIntegerMax) {
  932. [self setPhotoSelected:selectedButton.selected atIndex:index];
  933. }
  934. }
  935. - (void)playButtonTapped:(id)sender {
  936. // Ignore if we're already playing a video
  937. if (_currentVideoIndex != NSUIntegerMax) {
  938. return;
  939. }
  940. NSUInteger index = [self indexForPlayButton:sender];
  941. if (index != NSUIntegerMax) {
  942. if (!_currentVideoPlayerViewController) {
  943. [self playVideoAtIndex:index];
  944. }
  945. }
  946. }
  947. - (NSUInteger)indexForPlayButton:(UIView *)playButton {
  948. NSUInteger index = NSUIntegerMax;
  949. for (MWZoomingScrollView *page in _visiblePages) {
  950. if (page.playButton == playButton) {
  951. index = page.index;
  952. break;
  953. }
  954. }
  955. return index;
  956. }
  957. #pragma mark - Video
  958. - (void)playVideoAtIndex:(NSUInteger)index {
  959. id photo = [self photoAtIndex:index];
  960. if ([photo respondsToSelector:@selector(getVideoURL:)]) {
  961. // Valid for playing
  962. [self clearCurrentVideo];
  963. _currentVideoIndex = index;
  964. [self setVideoLoadingIndicatorVisible:YES atPageIndex:index];
  965. // Get video and play
  966. __typeof(self) __weak weakSelf = self;
  967. [photo getVideoURL:^(NSURL *url) {
  968. dispatch_async(dispatch_get_main_queue(), ^{
  969. // If the video is not playing anymore then bail
  970. __typeof(self) strongSelf = weakSelf;
  971. if (!strongSelf) return;
  972. if (strongSelf->_currentVideoIndex != index || !strongSelf->_viewIsActive) {
  973. return;
  974. }
  975. if (url) {
  976. [weakSelf _playVideo:url atPhotoIndex:index];
  977. } else {
  978. [weakSelf setVideoLoadingIndicatorVisible:NO atPageIndex:index];
  979. }
  980. });
  981. }];
  982. }
  983. }
  984. - (void)_playVideo:(NSURL *)videoURL atPhotoIndex:(NSUInteger)index {
  985. // Setup player
  986. _currentVideoPlayerViewController = [[AVPlayerViewController alloc] init];
  987. _currentVideoPlayerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  988. _currentVideoPlayerItem = [[AVPlayerItem alloc] initWithURL:videoURL];
  989. _currentVideoPlayerViewController.player = [[AVPlayer alloc] initWithPlayerItem:_currentVideoPlayerItem];
  990. _currentVideoPlayer = _currentVideoPlayerViewController.player;
  991. // Remove the movie player view controller from the "playback did finish" notification observers
  992. // Observe ourselves so we can get it to use the crossfade transition
  993. [[NSNotificationCenter defaultCenter] removeObserver:self
  994. name:AVPlayerItemDidPlayToEndTimeNotification
  995. object:_currentVideoPlayerItem];
  996. [[NSNotificationCenter defaultCenter] addObserver:self
  997. selector:@selector(videoFinishedCallback:)
  998. name:AVPlayerItemDidPlayToEndTimeNotification
  999. object:_currentVideoPlayerItem];
  1000. // Show
  1001. [self presentViewController:_currentVideoPlayerViewController animated:YES completion:^{
  1002. [_currentVideoPlayer play];
  1003. }];
  1004. }
  1005. - (void)videoFinishedCallback:(NSNotification*)notification {
  1006. // Remove observer
  1007. [[NSNotificationCenter defaultCenter] removeObserver:self
  1008. name:AVPlayerItemDidPlayToEndTimeNotification
  1009. object:_currentVideoPlayerItem];
  1010. // Clear up
  1011. [self clearCurrentVideo];
  1012. [self dismissViewControllerAnimated:YES completion:nil];
  1013. }
  1014. - (void)clearCurrentVideo {
  1015. [_currentVideoPlayerViewController.player pause];
  1016. [_currentVideoLoadingIndicator removeFromSuperview];
  1017. _currentVideoPlayerViewController = nil;
  1018. _currentVideoLoadingIndicator = nil;
  1019. _currentVideoPlayerItem = nil;
  1020. [[self pageDisplayedAtIndex:_currentVideoIndex] playButton].hidden = NO;
  1021. _currentVideoIndex = NSUIntegerMax;
  1022. }
  1023. - (void)setVideoLoadingIndicatorVisible:(BOOL)visible atPageIndex:(NSUInteger)pageIndex {
  1024. if (_currentVideoLoadingIndicator && !visible) {
  1025. [_currentVideoLoadingIndicator removeFromSuperview];
  1026. _currentVideoLoadingIndicator = nil;
  1027. [[self pageDisplayedAtIndex:pageIndex] playButton].hidden = NO;
  1028. } else if (!_currentVideoLoadingIndicator && visible) {
  1029. _currentVideoLoadingIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectZero];
  1030. [_currentVideoLoadingIndicator sizeToFit];
  1031. [_currentVideoLoadingIndicator startAnimating];
  1032. [_pagingScrollView addSubview:_currentVideoLoadingIndicator];
  1033. [self positionVideoLoadingIndicator];
  1034. [[self pageDisplayedAtIndex:pageIndex] playButton].hidden = YES;
  1035. }
  1036. }
  1037. - (void)positionVideoLoadingIndicator {
  1038. if (_currentVideoLoadingIndicator && _currentVideoIndex != NSUIntegerMax) {
  1039. CGRect frame = [self frameForPageAtIndex:_currentVideoIndex];
  1040. _currentVideoLoadingIndicator.center = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
  1041. }
  1042. }
  1043. #pragma mark - Control Hiding / Showing
  1044. // If permanent then we don't set timers to hide again
  1045. // Fades all controls on iOS 5 & 6, and iOS 7 controls slide and fade
  1046. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated permanent:(BOOL)permanent {
  1047. // Force visible
  1048. if (![self numberOfPhotos] || _alwaysShowControls)
  1049. hidden = NO;
  1050. // Cancel any timers
  1051. [self cancelControlHiding];
  1052. // Animations & positions
  1053. CGFloat animatonOffset = 20;
  1054. CGFloat animationDuration = (animated ? 0.35 : 0);
  1055. // Status bar
  1056. if (!_leaveStatusBarAlone) {
  1057. // Hide status bar
  1058. if (!_isVCBasedStatusBarAppearance) {
  1059. //TWS Non-view controller based
  1060. //[[UIApplication sharedApplication] setStatusBarHidden:hidden withAnimation:animated ? UIStatusBarAnimationSlide : UIStatusBarAnimationNone];
  1061. } else {
  1062. // View controller based so animate away
  1063. _statusBarShouldBeHidden = hidden;
  1064. //TWS
  1065. //[UIView animateWithDuration:animationDuration animations:^(void) {
  1066. // [self setNeedsStatusBarAppearanceUpdate];
  1067. //} completion:^(BOOL finished) {}];
  1068. }
  1069. }
  1070. // Toolbar, nav bar and captions
  1071. // Pre-appear animation positions for sliding
  1072. if ([self areControlsHidden] && !hidden && animated) {
  1073. // Toolbar
  1074. _toolbar.frame = CGRectOffset([self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]], 0, animatonOffset);
  1075. // Captions
  1076. for (MWZoomingScrollView *page in _visiblePages) {
  1077. if (page.captionView) {
  1078. MWCaptionView *v = page.captionView;
  1079. //TWS
  1080. id <MWPhoto> photo = [self photoAtIndex:self.currentIndex];
  1081. if (photo.caption) {
  1082. if ([photo caption]) v.label.text = photo.caption;
  1083. }
  1084. // Pass any index, all we're interested in is the Y
  1085. CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
  1086. captionFrame.origin.x = v.frame.origin.x; // Reset X
  1087. v.frame = CGRectOffset(captionFrame, 0, animatonOffset);
  1088. }
  1089. }
  1090. }
  1091. if ([_delegate respondsToSelector:@selector(setControlsHidden:animated:permanent:)]) {
  1092. [_delegate setControlsHidden:hidden animated:animated permanent:permanent];
  1093. }
  1094. [UIView animateWithDuration:animationDuration animations:^(void) {
  1095. CGFloat alpha = hidden ? 0 : 1;
  1096. // Nav bar slides up on it's own on iOS 7+
  1097. [self.navigationController.navigationBar setAlpha:alpha];
  1098. // Toolbar
  1099. _toolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  1100. if (hidden) _toolbar.frame = CGRectOffset(_toolbar.frame, 0, animatonOffset);
  1101. _toolbar.alpha = alpha;
  1102. // Captions
  1103. for (MWZoomingScrollView *page in _visiblePages) {
  1104. if (page.captionView) {
  1105. MWCaptionView *v = page.captionView;
  1106. // Pass any index, all we're interested in is the Y
  1107. CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
  1108. captionFrame.origin.x = v.frame.origin.x; // Reset X
  1109. if (hidden) captionFrame = CGRectOffset(captionFrame, 0, animatonOffset);
  1110. v.frame = captionFrame;
  1111. v.alpha = alpha;
  1112. }
  1113. }
  1114. // Selected buttons
  1115. for (MWZoomingScrollView *page in _visiblePages) {
  1116. if (page.selectedButton) {
  1117. UIButton *v = page.selectedButton;
  1118. CGRect newFrame = [self frameForSelectedButton:v atIndex:0];
  1119. newFrame.origin.x = v.frame.origin.x;
  1120. v.frame = newFrame;
  1121. }
  1122. }
  1123. } completion:^(BOOL finished) {}];
  1124. // Control hiding timer
  1125. // Will cancel existing timer but only begin hiding if
  1126. // they are visible
  1127. if (!permanent) [self hideControlsAfterDelay];
  1128. }
  1129. - (BOOL)prefersStatusBarHidden {
  1130. if (!_leaveStatusBarAlone) {
  1131. return _statusBarShouldBeHidden;
  1132. } else {
  1133. return [self presentingViewControllerPrefersStatusBarHidden];
  1134. }
  1135. }
  1136. - (UIStatusBarStyle)preferredStatusBarStyle {
  1137. return UIStatusBarStyleLightContent;
  1138. }
  1139. - (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
  1140. return UIStatusBarAnimationSlide;
  1141. }
  1142. - (void)cancelControlHiding {
  1143. // If a timer exists then cancel and release
  1144. if (_controlVisibilityTimer) {
  1145. [_controlVisibilityTimer invalidate];
  1146. _controlVisibilityTimer = nil;
  1147. }
  1148. }
  1149. // Enable/disable control visiblity timer
  1150. - (void)hideControlsAfterDelay {
  1151. if (![self areControlsHidden]) {
  1152. [self cancelControlHiding];
  1153. _controlVisibilityTimer = [NSTimer scheduledTimerWithTimeInterval:self.delayToHideElements target:self selector:@selector(hideControls) userInfo:nil repeats:NO];
  1154. }
  1155. }
  1156. - (BOOL)areControlsHidden {
  1157. return (_toolbar.alpha == 0);
  1158. }
  1159. - (void)hideControls { [self setControlsHidden:YES animated:YES permanent:NO]; }
  1160. - (void)showControls { [self setControlsHidden:NO animated:YES permanent:NO]; }
  1161. - (void)toggleControls { [self setControlsHidden:![self areControlsHidden] animated:YES permanent:NO]; }
  1162. #pragma mark - Properties
  1163. - (void)setCurrentPhotoIndex:(NSUInteger)index {
  1164. // Validate
  1165. NSUInteger photoCount = [self numberOfPhotos];
  1166. if (photoCount == 0) {
  1167. index = 0;
  1168. } else {
  1169. if (index >= photoCount)
  1170. index = [self numberOfPhotos]-1;
  1171. }
  1172. _currentPageIndex = index;
  1173. if ([self isViewLoaded]) {
  1174. [self jumpToPageAtIndex:index animated:NO];
  1175. if (!_viewIsActive)
  1176. [self tilePages]; // Force tiling if view is not visible
  1177. }
  1178. }
  1179. #pragma mark - Misc
  1180. - (void)doneButtonPressed:(id)sender {
  1181. // Only if we're modal and there's a done button
  1182. if (_doneButton) {
  1183. // Dismiss view controller
  1184. if ([_delegate respondsToSelector:@selector(photoBrowserDidFinishModalPresentation:)]) {
  1185. // Call delegate method and let them dismiss us
  1186. [_delegate photoBrowserDidFinishModalPresentation:self];
  1187. } else {
  1188. [self dismissViewControllerAnimated:YES completion:nil];
  1189. }
  1190. }
  1191. }
  1192. #pragma mark - Delete
  1193. - (void)deleteButtonPressed:(id)sender {
  1194. if ([self.delegate respondsToSelector:@selector(photoBrowser:deleteButtonPressedForPhotoAtIndex:deleteButton:)])
  1195. [self.delegate photoBrowser:self deleteButtonPressedForPhotoAtIndex:_currentPageIndex deleteButton:self.deleteButton];
  1196. }
  1197. #pragma mark - Share
  1198. - (void)shareButtonPressed:(id)sender {
  1199. if ([self.delegate respondsToSelector:@selector(photoBrowser:shareButtonPressedForPhotoAtIndex:)])
  1200. [self.delegate photoBrowser:self shareButtonPressedForPhotoAtIndex:_currentPageIndex];
  1201. }
  1202. #pragma mark - Actions
  1203. - (void)actionButtonPressed:(id)sender {
  1204. // Only react when image has loaded
  1205. id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
  1206. if ([self numberOfPhotos] > 0 && [photo underlyingImage]) {
  1207. // If they have defined a delegate method then just message them
  1208. if ([self.delegate respondsToSelector:@selector(photoBrowser:actionButtonPressedForPhotoAtIndex:)]) {
  1209. // Let delegate handle things
  1210. [self.delegate photoBrowser:self actionButtonPressedForPhotoAtIndex:_currentPageIndex];
  1211. } else {
  1212. // Show activity view controller
  1213. NSMutableArray *items = [NSMutableArray arrayWithObject:[photo underlyingImage]];
  1214. if (photo.caption) {
  1215. [items addObject:photo.caption];
  1216. }
  1217. self.activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
  1218. // Show
  1219. typeof(self) __weak weakSelf = self;
  1220. [self.activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  1221. weakSelf.activityViewController = nil;
  1222. [weakSelf hideControlsAfterDelay];
  1223. }];
  1224. // iOS 8 - Set the Anchor Point for the popover
  1225. if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8")) {
  1226. self.activityViewController.popoverPresentationController.barButtonItem = _actionButton;
  1227. }
  1228. [self presentViewController:self.activityViewController animated:YES completion:nil];
  1229. }
  1230. // Keep controls hidden
  1231. [self setControlsHidden:NO animated:YES permanent:YES];
  1232. }
  1233. }
  1234. @end