MWPhotoBrowser.m 53 KB

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