MWPhotoBrowser.m 51 KB

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