MWPhotoBrowser.m 58 KB

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