MWPhotoBrowser.m 64 KB

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