MWPhotoBrowser.m 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  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. }
  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. // Only if we're modal and there's a done button
  1134. if (_doneButton) {
  1135. // Dismiss view controller
  1136. if ([_delegate respondsToSelector:@selector(photoBrowserDidFinishModalPresentation:)]) {
  1137. // Call delegate method and let them dismiss us
  1138. [_delegate photoBrowserDidFinishModalPresentation:self];
  1139. } else {
  1140. [self dismissViewControllerAnimated:YES completion:nil];
  1141. }
  1142. }
  1143. }
  1144. #pragma mark - Delete
  1145. - (void)deleteButtonPressed:(id)sender {
  1146. if ([self.delegate respondsToSelector:@selector(photoBrowser:deleteButtonPressedForPhotoAtIndex:deleteButton:)])
  1147. [self.delegate photoBrowser:self deleteButtonPressedForPhotoAtIndex:_currentPageIndex deleteButton:self.deleteButton];
  1148. }
  1149. #pragma mark - Share
  1150. - (void)shareButtonPressed:(id)sender {
  1151. if ([self.delegate respondsToSelector:@selector(photoBrowser:shareButtonPressedForPhotoAtIndex:)])
  1152. [self.delegate photoBrowser:self shareButtonPressedForPhotoAtIndex:_currentPageIndex];
  1153. }
  1154. #pragma mark - Actions
  1155. - (void)actionButtonPressed:(id)sender {
  1156. // Only react when image has loaded
  1157. id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
  1158. if ([self numberOfPhotos] > 0 && [photo underlyingImage]) {
  1159. // If they have defined a delegate method then just message them
  1160. if ([self.delegate respondsToSelector:@selector(photoBrowser:actionButtonPressedForPhotoAtIndex:)]) {
  1161. // Let delegate handle things
  1162. [self.delegate photoBrowser:self actionButtonPressedForPhotoAtIndex:_currentPageIndex];
  1163. } else {
  1164. // Show activity view controller
  1165. NSMutableArray *items = [NSMutableArray arrayWithObject:[photo underlyingImage]];
  1166. if (photo.caption) {
  1167. [items addObject:photo.caption];
  1168. }
  1169. self.activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
  1170. // Show
  1171. typeof(self) __weak weakSelf = self;
  1172. [self.activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  1173. weakSelf.activityViewController = nil;
  1174. [weakSelf hideControlsAfterDelay];
  1175. }];
  1176. // iOS 8 - Set the Anchor Point for the popover
  1177. if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8")) {
  1178. self.activityViewController.popoverPresentationController.barButtonItem = _actionButton;
  1179. }
  1180. [self presentViewController:self.activityViewController animated:YES completion:nil];
  1181. }
  1182. // Keep controls hidden
  1183. [self setControlsHidden:NO animated:YES permanent:YES];
  1184. }
  1185. }
  1186. @end