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