MWPhotoBrowser.m 58 KB

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