2
0

MWPhotoBrowser.m 61 KB

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