MWPhotoBrowser.m 51 KB

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