| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667 |
- //
- // MWPhotoBrowser.m
- // MWPhotoBrowser
- //
- // Created by Michael Waterfall on 14/10/2010.
- // Copyright 2010 d3i. All rights reserved.
- //
- #import <QuartzCore/QuartzCore.h>
- #import "MWCommon.h"
- #import "MWPhotoBrowser.h"
- #import "MWPhotoBrowserPrivate.h"
- #import "EMSDImageCache.h"
- #import "EaseLocalDefine.h"
- #define PADDING 10
- #define ACTION_SHEET_OLD_ACTIONS 2000
- @implementation MWPhotoBrowser
- #pragma mark - Init
- - (id)init {
- if ((self = [super init])) {
- [self _initialisation];
- }
- return self;
- }
- - (id)initWithDelegate:(id <MWPhotoBrowserDelegate>)delegate {
- if ((self = [self init])) {
- _delegate = delegate;
- }
- return self;
- }
- - (id)initWithPhotos:(NSArray *)photosArray {
- if ((self = [self init])) {
- _depreciatedPhotoData = photosArray;
- }
- return self;
- }
- - (id)initWithCoder:(NSCoder *)decoder {
- if ((self = [super initWithCoder:decoder])) {
- [self _initialisation];
- }
- return self;
- }
- - (void)_initialisation {
-
- // Defaults
- NSNumber *isVCBasedStatusBarAppearanceNum = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"];
- if (isVCBasedStatusBarAppearanceNum) {
- _isVCBasedStatusBarAppearance = isVCBasedStatusBarAppearanceNum.boolValue;
- } else {
- _isVCBasedStatusBarAppearance = YES; // default
- }
- #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
- if (SYSTEM_VERSION_LESS_THAN(@"7")) self.wantsFullScreenLayout = YES;
- #endif
- self.hidesBottomBarWhenPushed = YES;
- _hasBelongedToViewController = NO;
- _photoCount = NSNotFound;
- _previousLayoutBounds = CGRectZero;
- _currentPageIndex = 0;
- _previousPageIndex = NSUIntegerMax;
- _displayActionButton = YES;
- _displayNavArrows = NO;
- _zoomPhotosToFill = YES;
- _performingLayout = NO; // Reset on view did appear
- _rotating = NO;
- _viewIsActive = NO;
- _enableGrid = YES;
- _startOnGrid = NO;
- _enableSwipeToDismiss = YES;
- _delayToHideElements = 5;
- _visiblePages = [[NSMutableSet alloc] init];
- _recycledPages = [[NSMutableSet alloc] init];
- _photos = [[NSMutableArray alloc] init];
- _thumbPhotos = [[NSMutableArray alloc] init];
- _currentGridContentOffset = CGPointMake(0, CGFLOAT_MAX);
- _didSavePreviousStateOfNavBar = NO;
- if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]){
- self.automaticallyAdjustsScrollViewInsets = NO;
- }
-
- // Listen for MWPhoto notifications
- [[NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(handleMWPhotoLoadingDidEndNotification:)
- name:MWPHOTO_LOADING_DID_END_NOTIFICATION
- object:nil];
-
- }
- - (void)dealloc {
- _pagingScrollView.delegate = nil;
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- [self releaseAllUnderlyingPhotos:NO];
- [[EMSDImageCache sharedImageCache] clearMemory]; // clear memory
- }
- - (void)releaseAllUnderlyingPhotos:(BOOL)preserveCurrent {
- // Create a copy in case this array is modified while we are looping through
- // Release photos
- NSArray *copy = [_photos copy];
- for (id p in copy) {
- if (p != [NSNull null]) {
- if (preserveCurrent && p == [self photoAtIndex:self.currentIndex]) {
- continue; // skip current
- }
- [p unloadUnderlyingImage];
- }
- }
- // Release thumbs
- copy = [_thumbPhotos copy];
- for (id p in copy) {
- if (p != [NSNull null]) {
- [p unloadUnderlyingImage];
- }
- }
- }
- - (void)didReceiveMemoryWarning {
- // Release any cached data, images, etc that aren't in use.
- [self releaseAllUnderlyingPhotos:YES];
- [_recycledPages removeAllObjects];
-
- // Releases the view if it doesn't have a superview.
- [super didReceiveMemoryWarning];
-
- }
- #pragma mark - View Loading
- // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- - (void)viewDidLoad {
-
- // Validate grid settings
- if (_startOnGrid) _enableGrid = YES;
- if (_enableGrid) {
- _enableGrid = [_delegate respondsToSelector:@selector(photoBrowser:thumbPhotoAtIndex:)];
- }
- if (!_enableGrid) _startOnGrid = NO;
-
- // View
- self.view.backgroundColor = [UIColor blackColor];
- self.view.clipsToBounds = YES;
-
- // Setup paging scrolling view
- CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
- _pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame];
- _pagingScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
- _pagingScrollView.pagingEnabled = YES;
- _pagingScrollView.delegate = self;
- _pagingScrollView.showsHorizontalScrollIndicator = NO;
- _pagingScrollView.showsVerticalScrollIndicator = NO;
- _pagingScrollView.backgroundColor = [UIColor blackColor];
- _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
- [self.view addSubview:_pagingScrollView];
-
- // Toolbar
- _toolbar = [[UIToolbar alloc] initWithFrame:[self frameForToolbarAtOrientation:self.interfaceOrientation]];
- _toolbar.tintColor = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7") ? [UIColor whiteColor] : nil;
- if ([_toolbar respondsToSelector:@selector(setBarTintColor:)]) {
- _toolbar.barTintColor = nil;
- }
- if ([[UIToolbar class] respondsToSelector:@selector(appearance)]) {
- [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
- [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsLandscapePhone];
- }
- _toolbar.barStyle = UIBarStyleBlackTranslucent;
- _toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
-
- // Toolbar Items
- if (self.displayNavArrows) {
- NSString *arrowPathFormat;
- if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) {
- arrowPathFormat = @"MWPhotoBrowser.bundle/images/UIBarButtonItemArrowOutline%@.png";
- } else {
- arrowPathFormat = @"MWPhotoBrowser.bundle/images/UIBarButtonItemArrow%@.png";
- }
- _previousButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:arrowPathFormat, @"Left"]] style:UIBarButtonItemStylePlain target:self action:@selector(gotoPreviousPage)];
- _nextButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:arrowPathFormat, @"Right"]] style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextPage)];
- }
- if (self.displayActionButton) {
- _actionButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionButtonPressed:)];
- }
-
- // Update
- [self reloadData];
-
- // Swipe to dismiss
- if (_enableSwipeToDismiss) {
- UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doneButtonPressed:)];
- swipeGesture.direction = UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp;
- [self.view addGestureRecognizer:swipeGesture];
- }
-
- // Super
- [super viewDidLoad];
-
- }
- - (void)performLayout {
-
- // Setup
- _performingLayout = YES;
- NSUInteger numberOfPhotos = [self numberOfPhotos];
-
- // Setup pages
- [_visiblePages removeAllObjects];
- [_recycledPages removeAllObjects];
-
- // Navigation buttons
- if ([self.navigationController.viewControllers objectAtIndex:0] == self) {
- // We're first on stack so show done button
- _doneButton = [[UIBarButtonItem alloc] initWithTitle:NSEaseLocalizedString(@"Done", nil) style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed:)];
- // Set appearance
- if ([UIBarButtonItem respondsToSelector:@selector(appearance)]) {
- [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
- [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsLandscapePhone];
- [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
- [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsLandscapePhone];
- [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
- [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
- }
- self.navigationItem.rightBarButtonItem = _doneButton;
- } else {
- // We're not first so show back button
- UIViewController *previousViewController = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2];
- NSString *backButtonTitle = previousViewController.navigationItem.backBarButtonItem ? previousViewController.navigationItem.backBarButtonItem.title : previousViewController.title;
- UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:backButtonTitle style:UIBarButtonItemStylePlain target:nil action:nil];
- // Appearance
- if ([UIBarButtonItem respondsToSelector:@selector(appearance)]) {
- [newBackButton setBackButtonBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
- [newBackButton setBackButtonBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsLandscapePhone];
- [newBackButton setBackButtonBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
- [newBackButton setBackButtonBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsLandscapePhone];
- [newBackButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
- [newBackButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
- }
- _previousViewControllerBackButton = previousViewController.navigationItem.backBarButtonItem; // remember previous
- previousViewController.navigationItem.backBarButtonItem = newBackButton;
- }
- // Toolbar items
- BOOL hasItems = NO;
- UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
- fixedSpace.width = 32; // To balance action button
- UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
- NSMutableArray *items = [[NSMutableArray alloc] init];
- // Left button - Grid
- if (_enableGrid) {
- hasItems = YES;
- NSString *buttonName = @"UIBarButtonItemGrid";
- if (SYSTEM_VERSION_LESS_THAN(@"7")) buttonName = @"UIBarButtonItemGridiOS6";
- [items addObject:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"MWPhotoBrowser.bundle/images/%@.png", buttonName]] style:UIBarButtonItemStylePlain target:self action:@selector(showGridAnimated)]];
- } else {
- [items addObject:fixedSpace];
- }
- // Middle - Nav
- if (_previousButton && _nextButton && numberOfPhotos > 1) {
- hasItems = YES;
- [items addObject:flexSpace];
- [items addObject:_previousButton];
- [items addObject:flexSpace];
- [items addObject:_nextButton];
- [items addObject:flexSpace];
- } else {
- [items addObject:flexSpace];
- }
- // Right - Action
- if (_actionButton && !(!hasItems && !self.navigationItem.rightBarButtonItem)) {
- [items addObject:_actionButton];
- } else {
- // We're not showing the toolbar so try and show in top right
- if (_actionButton)
- self.navigationItem.rightBarButtonItem = _actionButton;
- [items addObject:fixedSpace];
- }
- // Toolbar visibility
- [_toolbar setItems:items];
- BOOL hideToolbar = YES;
- for (UIBarButtonItem* item in _toolbar.items) {
- if (item != fixedSpace && item != flexSpace) {
- hideToolbar = NO;
- break;
- }
- }
- if (hideToolbar) {
- [_toolbar removeFromSuperview];
- } else {
- [self.view addSubview:_toolbar];
- }
-
- // Update nav
- [self updateNavigation];
-
- // Content offset
- _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:_currentPageIndex];
- [self tilePages];
- _performingLayout = NO;
-
- }
- // Release any retained subviews of the main view.
- - (void)viewDidUnload {
- _currentPageIndex = 0;
- _pagingScrollView = nil;
- _visiblePages = nil;
- _recycledPages = nil;
- _toolbar = nil;
- _previousButton = nil;
- _nextButton = nil;
- _progressHUD = nil;
- [super viewDidUnload];
- }
- - (BOOL)presentingViewControllerPrefersStatusBarHidden {
- UIViewController *presenting = self.presentingViewController;
- if (presenting) {
- if ([presenting isKindOfClass:[UINavigationController class]]) {
- presenting = [(UINavigationController *)presenting topViewController];
- }
- } else {
- // We're in a navigation controller so get previous one!
- if (self.navigationController && self.navigationController.viewControllers.count > 1) {
- presenting = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2];
- }
- }
- if (presenting) {
- return [presenting prefersStatusBarHidden];
- } else {
- return NO;
- }
- }
- #pragma mark - Appearance
- - (void)viewWillAppear:(BOOL)animated {
-
- // Super
- [super viewWillAppear:animated];
-
- // Status bar
- if ([UIViewController instancesRespondToSelector:@selector(prefersStatusBarHidden)]) {
- _leaveStatusBarAlone = [self presentingViewControllerPrefersStatusBarHidden];
- } else {
- _leaveStatusBarAlone = [UIApplication sharedApplication].statusBarHidden;
- }
- if (CGRectEqualToRect([[UIApplication sharedApplication] statusBarFrame], CGRectZero)) {
- // If the frame is zero then definitely leave it alone
- _leaveStatusBarAlone = YES;
- }
- BOOL fullScreen = YES;
- #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
- if (SYSTEM_VERSION_LESS_THAN(@"7")) fullScreen = self.wantsFullScreenLayout;
- #endif
- if (!_leaveStatusBarAlone && fullScreen && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
- _previousStatusBarStyle = [[UIApplication sharedApplication] statusBarStyle];
- if (SYSTEM_VERSION_LESS_THAN(@"7")) {
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wdeprecated-declarations"
- [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:animated];
- #pragma clang diagnostic push
- } else {
- [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:animated];
- }
- }
-
- // Navigation bar appearance
- if (!_viewIsActive && [self.navigationController.viewControllers objectAtIndex:0] != self) {
- [self storePreviousNavBarAppearance];
- }
- [self setNavBarAppearance:animated];
-
- // Update UI
- [self hideControlsAfterDelay];
-
- // Initial appearance
- if (!_viewHasAppearedInitially) {
- if (_startOnGrid) {
- [self showGrid:NO];
- }
- _viewHasAppearedInitially = YES;
- }
- }
- - (void)viewWillDisappear:(BOOL)animated {
-
- // Check that we're being popped for good
- if ([self.navigationController.viewControllers objectAtIndex:0] != self &&
- ![self.navigationController.viewControllers containsObject:self]) {
-
- // State
- _viewIsActive = NO;
-
- // Bar state / appearance
- [self restorePreviousNavBarAppearance:animated];
-
- }
-
- // Controls
- [self.navigationController.navigationBar.layer removeAllAnimations]; // Stop all animations on nav bar
- [NSObject cancelPreviousPerformRequestsWithTarget:self]; // Cancel any pending toggles from taps
- [self setControlsHidden:NO animated:NO permanent:YES];
-
- // Status bar
- BOOL fullScreen = YES;
- #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
- if (SYSTEM_VERSION_LESS_THAN(@"7")) fullScreen = self.wantsFullScreenLayout;
- #endif
- if (!_leaveStatusBarAlone && fullScreen && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
- [[UIApplication sharedApplication] setStatusBarStyle:_previousStatusBarStyle animated:animated];
- }
-
- // Super
- [super viewWillDisappear:animated];
-
- }
- - (void)viewDidAppear:(BOOL)animated {
- [super viewDidAppear:animated];
- _viewIsActive = YES;
- }
- - (void)willMoveToParentViewController:(UIViewController *)parent {
- if (parent && _hasBelongedToViewController) {
- [NSException raise:@"MWPhotoBrowser Instance Reuse" format:@"MWPhotoBrowser instances cannot be reused."];
- }
- }
- - (void)didMoveToParentViewController:(UIViewController *)parent {
- if (!parent) _hasBelongedToViewController = YES;
- }
- #pragma mark - Nav Bar Appearance
- - (void)setNavBarAppearance:(BOOL)animated {
- [self.navigationController setNavigationBarHidden:NO animated:animated];
- UINavigationBar *navBar = self.navigationController.navigationBar;
- navBar.tintColor = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7") ? [UIColor whiteColor] : nil;
- if ([navBar respondsToSelector:@selector(setBarTintColor:)]) {
- navBar.barTintColor = nil;
- navBar.shadowImage = nil;
- }
- navBar.translucent = YES;
- navBar.barStyle = UIBarStyleBlackTranslucent;
- if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) {
- [navBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
- [navBar setBackgroundImage:nil forBarMetrics:UIBarMetricsLandscapePhone];
- }
- }
- - (void)storePreviousNavBarAppearance {
- _didSavePreviousStateOfNavBar = YES;
- if ([UINavigationBar instancesRespondToSelector:@selector(barTintColor)]) {
- _previousNavBarBarTintColor = self.navigationController.navigationBar.barTintColor;
- }
- _previousNavBarTranslucent = self.navigationController.navigationBar.translucent;
- _previousNavBarTintColor = self.navigationController.navigationBar.tintColor;
- _previousNavBarHidden = self.navigationController.navigationBarHidden;
- _previousNavBarStyle = self.navigationController.navigationBar.barStyle;
- if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) {
- _previousNavigationBarBackgroundImageDefault = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault];
- _previousNavigationBarBackgroundImageLandscapePhone = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsLandscapePhone];
- }
- }
- - (void)restorePreviousNavBarAppearance:(BOOL)animated {
- if (_didSavePreviousStateOfNavBar) {
- [self.navigationController setNavigationBarHidden:_previousNavBarHidden animated:animated];
- UINavigationBar *navBar = self.navigationController.navigationBar;
- navBar.tintColor = _previousNavBarTintColor;
- navBar.translucent = _previousNavBarTranslucent;
- if ([UINavigationBar instancesRespondToSelector:@selector(barTintColor)]) {
- navBar.barTintColor = _previousNavBarBarTintColor;
- }
- navBar.barStyle = _previousNavBarStyle;
- if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) {
- [navBar setBackgroundImage:_previousNavigationBarBackgroundImageDefault forBarMetrics:UIBarMetricsDefault];
- [navBar setBackgroundImage:_previousNavigationBarBackgroundImageLandscapePhone forBarMetrics:UIBarMetricsLandscapePhone];
- }
- // Restore back button if we need to
- if (_previousViewControllerBackButton) {
- UIViewController *previousViewController = [self.navigationController topViewController]; // We've disappeared so previous is now top
- previousViewController.navigationItem.backBarButtonItem = _previousViewControllerBackButton;
- _previousViewControllerBackButton = nil;
- }
- }
- }
- #pragma mark - Layout
- - (void)viewWillLayoutSubviews {
- [super viewWillLayoutSubviews];
- [self layoutVisiblePages];
- }
- - (void)layoutVisiblePages {
-
- // Flag
- _performingLayout = YES;
-
- // Toolbar
- _toolbar.frame = [self frameForToolbarAtOrientation:self.interfaceOrientation];
-
- // Remember index
- NSUInteger indexPriorToLayout = _currentPageIndex;
-
- // Get paging scroll view frame to determine if anything needs changing
- CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
-
- // Frame needs changing
- if (!_skipNextPagingScrollViewPositioning) {
- _pagingScrollView.frame = pagingScrollViewFrame;
- }
- _skipNextPagingScrollViewPositioning = NO;
-
- // Recalculate contentSize based on current orientation
- _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
-
- // Adjust frames and configuration of each visible page
- for (MWZoomingScrollView *page in _visiblePages) {
- NSUInteger index = page.index;
- page.frame = [self frameForPageAtIndex:index];
- if (page.captionView) {
- page.captionView.frame = [self frameForCaptionView:page.captionView atIndex:index];
- }
- if (page.selectedButton) {
- page.selectedButton.frame = [self frameForSelectedButton:page.selectedButton atIndex:index];
- }
-
- // Adjust scales if bounds has changed since last time
- if (!CGRectEqualToRect(_previousLayoutBounds, self.view.bounds)) {
- // Update zooms for new bounds
- [page setMaxMinZoomScalesForCurrentBounds];
- _previousLayoutBounds = self.view.bounds;
- }
- }
-
- // Adjust contentOffset to preserve page location based on values collected prior to location
- _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:indexPriorToLayout];
- [self didStartViewingPageAtIndex:_currentPageIndex]; // initial
-
- // Reset
- _currentPageIndex = indexPriorToLayout;
- _performingLayout = NO;
-
- }
- #pragma mark - Rotation
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
- return YES;
- }
- - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
- return UIInterfaceOrientationMaskAll;
- }
- - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
-
- // Remember page index before rotation
- _pageIndexBeforeRotation = _currentPageIndex;
- _rotating = YES;
-
- // In iOS 7 the nav bar gets shown after rotation, but might as well do this for everything!
- if ([self areControlsHidden]) {
- // Force hidden
- self.navigationController.navigationBarHidden = YES;
- }
-
- }
- - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
-
- // Perform layout
- _currentPageIndex = _pageIndexBeforeRotation;
-
- // Delay control holding
- [self hideControlsAfterDelay];
-
- // Layout
- [self layoutVisiblePages];
-
- }
- - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
- _rotating = NO;
- // Ensure nav bar isn't re-displayed
- if ([self areControlsHidden]) {
- self.navigationController.navigationBarHidden = NO;
- self.navigationController.navigationBar.alpha = 0;
- }
- }
- #pragma mark - Data
- - (NSUInteger)currentIndex {
- return _currentPageIndex;
- }
- - (void)reloadData {
-
- // Reset
- _photoCount = NSNotFound;
-
- // Get data
- NSUInteger numberOfPhotos = [self numberOfPhotos];
- [self releaseAllUnderlyingPhotos:YES];
- [_photos removeAllObjects];
- [_thumbPhotos removeAllObjects];
- for (int i = 0; i < numberOfPhotos; i++) {
- [_photos addObject:[NSNull null]];
- [_thumbPhotos addObject:[NSNull null]];
- }
- // Update current page index
- if (numberOfPhotos > 0) {
- _currentPageIndex = MAX(0, MIN(_currentPageIndex, numberOfPhotos - 1));
- } else {
- _currentPageIndex = 0;
- }
-
- // Update layout
- if ([self isViewLoaded]) {
- while (_pagingScrollView.subviews.count) {
- [[_pagingScrollView.subviews lastObject] removeFromSuperview];
- }
- [self performLayout];
- [self.view setNeedsLayout];
- }
-
- }
- - (NSUInteger)numberOfPhotos {
- if (_photoCount == NSNotFound) {
- if ([_delegate respondsToSelector:@selector(numberOfPhotosInPhotoBrowser:)]) {
- _photoCount = [_delegate numberOfPhotosInPhotoBrowser:self];
- } else if (_depreciatedPhotoData) {
- _photoCount = _depreciatedPhotoData.count;
- }
- }
- if (_photoCount == NSNotFound) _photoCount = 0;
- return _photoCount;
- }
- - (id<MWPhoto>)photoAtIndex:(NSUInteger)index {
- id <MWPhoto> photo = nil;
- if (index < _photos.count) {
- if ([_photos objectAtIndex:index] == [NSNull null]) {
- if ([_delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:)]) {
- photo = [_delegate photoBrowser:self photoAtIndex:index];
- } else if (_depreciatedPhotoData && index < _depreciatedPhotoData.count) {
- photo = [_depreciatedPhotoData objectAtIndex:index];
- }
- if (photo) [_photos replaceObjectAtIndex:index withObject:photo];
- } else {
- photo = [_photos objectAtIndex:index];
- }
- }
- return photo;
- }
- - (id<MWPhoto>)thumbPhotoAtIndex:(NSUInteger)index {
- id <MWPhoto> photo = nil;
- if (index < _thumbPhotos.count) {
- if ([_thumbPhotos objectAtIndex:index] == [NSNull null]) {
- if ([_delegate respondsToSelector:@selector(photoBrowser:thumbPhotoAtIndex:)]) {
- photo = [_delegate photoBrowser:self thumbPhotoAtIndex:index];
- }
- if (photo) [_thumbPhotos replaceObjectAtIndex:index withObject:photo];
- } else {
- photo = [_thumbPhotos objectAtIndex:index];
- }
- }
- return photo;
- }
- - (MWCaptionView *)captionViewForPhotoAtIndex:(NSUInteger)index {
- MWCaptionView *captionView = nil;
- if ([_delegate respondsToSelector:@selector(photoBrowser:captionViewForPhotoAtIndex:)]) {
- captionView = [_delegate photoBrowser:self captionViewForPhotoAtIndex:index];
- } else {
- id <MWPhoto> photo = [self photoAtIndex:index];
- if ([photo respondsToSelector:@selector(caption)]) {
- if ([photo caption]) captionView = [[MWCaptionView alloc] initWithPhoto:photo];
- }
- }
- captionView.alpha = [self areControlsHidden] ? 0 : 1; // Initial alpha
- return captionView;
- }
- - (BOOL)photoIsSelectedAtIndex:(NSUInteger)index {
- BOOL value = NO;
- if (_displaySelectionButtons) {
- if ([self.delegate respondsToSelector:@selector(photoBrowser:isPhotoSelectedAtIndex:)]) {
- value = [self.delegate photoBrowser:self isPhotoSelectedAtIndex:index];
- }
- }
- return value;
- }
- - (void)setPhotoSelected:(BOOL)selected atIndex:(NSUInteger)index {
- if (_displaySelectionButtons) {
- if ([self.delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:selectedChanged:)]) {
- [self.delegate photoBrowser:self photoAtIndex:index selectedChanged:selected];
- }
- }
- }
- - (UIImage *)imageForPhoto:(id<MWPhoto>)photo {
- if (photo) {
- // Get image or obtain in background
- if ([photo underlyingImage]) {
- return [photo underlyingImage];
- } else {
- [photo loadUnderlyingImageAndNotify];
- }
- }
- return nil;
- }
- - (void)loadAdjacentPhotosIfNecessary:(id<MWPhoto>)photo {
- MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
- if (page) {
- // If page is current page then initiate loading of previous and next pages
- NSUInteger pageIndex = page.index;
- if (_currentPageIndex == pageIndex) {
- if (pageIndex > 0) {
- // Preload index - 1
- id <MWPhoto> photo = [self photoAtIndex:pageIndex-1];
- if (![photo underlyingImage]) {
- [photo loadUnderlyingImageAndNotify];
- MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex-1);
- }
- }
- if (pageIndex < [self numberOfPhotos] - 1) {
- // Preload index + 1
- id <MWPhoto> photo = [self photoAtIndex:pageIndex+1];
- if (![photo underlyingImage]) {
- [photo loadUnderlyingImageAndNotify];
- MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex+1);
- }
- }
- }
- }
- }
- #pragma mark - MWPhoto Loading Notification
- - (void)handleMWPhotoLoadingDidEndNotification:(NSNotification *)notification {
- id <MWPhoto> photo = [notification object];
- MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
- if (page) {
- if ([photo underlyingImage]) {
- // Successful load
- [page displayImage];
- [self loadAdjacentPhotosIfNecessary:photo];
- } else {
- // Failed to load
- [page displayImageFailure];
- }
- // Update nav
- [self updateNavigation];
- }
- }
- #pragma mark - Paging
- - (void)tilePages {
-
- // Calculate which pages should be visible
- // Ignore padding as paging bounces encroach on that
- // and lead to false page loads
- CGRect visibleBounds = _pagingScrollView.bounds;
- NSInteger iFirstIndex = (NSInteger)floorf((CGRectGetMinX(visibleBounds)+PADDING*2) / CGRectGetWidth(visibleBounds));
- NSInteger iLastIndex = (NSInteger)floorf((CGRectGetMaxX(visibleBounds)-PADDING*2-1) / CGRectGetWidth(visibleBounds));
- if (iFirstIndex < 0) iFirstIndex = 0;
- if (iFirstIndex > [self numberOfPhotos] - 1) iFirstIndex = [self numberOfPhotos] - 1;
- if (iLastIndex < 0) iLastIndex = 0;
- if (iLastIndex > [self numberOfPhotos] - 1) iLastIndex = [self numberOfPhotos] - 1;
-
- // Recycle no longer needed pages
- NSInteger pageIndex;
- for (MWZoomingScrollView *page in _visiblePages) {
- pageIndex = page.index;
- if (pageIndex < (NSUInteger)iFirstIndex || pageIndex > (NSUInteger)iLastIndex) {
- [_recycledPages addObject:page];
- [page.captionView removeFromSuperview];
- [page.selectedButton removeFromSuperview];
- [page prepareForReuse];
- [page removeFromSuperview];
- MWLog(@"Removed page at index %lu", (unsigned long)pageIndex);
- }
- }
- [_visiblePages minusSet:_recycledPages];
- while (_recycledPages.count > 2) // Only keep 2 recycled pages
- [_recycledPages removeObject:[_recycledPages anyObject]];
-
- // Add missing pages
- for (NSUInteger index = (NSUInteger)iFirstIndex; index <= (NSUInteger)iLastIndex; index++) {
- if (![self isDisplayingPageForIndex:index]) {
-
- // Add new page
- MWZoomingScrollView *page = [self dequeueRecycledPage];
- if (!page) {
- page = [[MWZoomingScrollView alloc] initWithPhotoBrowser:self];
- }
- [_visiblePages addObject:page];
- [self configurePage:page forIndex:index];
- [_pagingScrollView addSubview:page];
- MWLog(@"Added page at index %lu", (unsigned long)index);
-
- // Add caption
- MWCaptionView *captionView = [self captionViewForPhotoAtIndex:index];
- if (captionView) {
- captionView.frame = [self frameForCaptionView:captionView atIndex:index];
- [_pagingScrollView addSubview:captionView];
- page.captionView = captionView;
- }
-
- // Add selected button
- if (self.displaySelectionButtons) {
- UIButton *selectedButton = [UIButton buttonWithType:UIButtonTypeCustom];
- [selectedButton setImage:[UIImage imageNamed:@"MWPhotoBrowser.bundle/images/ImageSelectedOff.png"] forState:UIControlStateNormal];
- [selectedButton setImage:[UIImage imageNamed:@"MWPhotoBrowser.bundle/images/ImageSelectedOn.png"] forState:UIControlStateSelected];
- [selectedButton sizeToFit];
- selectedButton.adjustsImageWhenHighlighted = NO;
- [selectedButton addTarget:self action:@selector(selectedButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
- selectedButton.frame = [self frameForSelectedButton:selectedButton atIndex:index];
- [_pagingScrollView addSubview:selectedButton];
- page.selectedButton = selectedButton;
- selectedButton.selected = [self photoIsSelectedAtIndex:index];
- }
-
- }
- }
-
- }
- - (void)updateVisiblePageStates {
- NSSet *copy = [_visiblePages copy];
- for (MWZoomingScrollView *page in copy) {
-
- // Update selection
- page.selectedButton.selected = [self photoIsSelectedAtIndex:page.index];
-
- }
- }
- - (BOOL)isDisplayingPageForIndex:(NSUInteger)index {
- for (MWZoomingScrollView *page in _visiblePages)
- if (page.index == index) return YES;
- return NO;
- }
- - (MWZoomingScrollView *)pageDisplayedAtIndex:(NSUInteger)index {
- MWZoomingScrollView *thePage = nil;
- for (MWZoomingScrollView *page in _visiblePages) {
- if (page.index == index) {
- thePage = page; break;
- }
- }
- return thePage;
- }
- - (MWZoomingScrollView *)pageDisplayingPhoto:(id<MWPhoto>)photo {
- MWZoomingScrollView *thePage = nil;
- for (MWZoomingScrollView *page in _visiblePages) {
- if (page.photo == photo) {
- thePage = page; break;
- }
- }
- return thePage;
- }
- - (void)configurePage:(MWZoomingScrollView *)page forIndex:(NSUInteger)index {
- page.frame = [self frameForPageAtIndex:index];
- page.index = index;
- page.photo = [self photoAtIndex:index];
- }
- - (MWZoomingScrollView *)dequeueRecycledPage {
- MWZoomingScrollView *page = [_recycledPages anyObject];
- if (page) {
- [_recycledPages removeObject:page];
- }
- return page;
- }
- // Handle page changes
- - (void)didStartViewingPageAtIndex:(NSUInteger)index {
-
- if (![self numberOfPhotos]) {
- // Show controls
- [self setControlsHidden:NO animated:YES permanent:YES];
- return;
- }
-
- // Release images further away than +/-1
- NSUInteger i;
- if (index > 0) {
- // Release anything < index - 1
- for (i = 0; i < index-1; i++) {
- id photo = [_photos objectAtIndex:i];
- if (photo != [NSNull null]) {
- [photo unloadUnderlyingImage];
- [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
- MWLog(@"Released underlying image at index %lu", (unsigned long)i);
- }
- }
- }
- if (index < [self numberOfPhotos] - 1) {
- // Release anything > index + 1
- for (i = index + 2; i < _photos.count; i++) {
- id photo = [_photos objectAtIndex:i];
- if (photo != [NSNull null]) {
- [photo unloadUnderlyingImage];
- [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
- MWLog(@"Released underlying image at index %lu", (unsigned long)i);
- }
- }
- }
-
- // Load adjacent images if needed and the photo is already
- // loaded. Also called after photo has been loaded in background
- id <MWPhoto> currentPhoto = [self photoAtIndex:index];
- if ([currentPhoto underlyingImage]) {
- // photo loaded so load ajacent now
- [self loadAdjacentPhotosIfNecessary:currentPhoto];
- }
-
- // Notify delegate
- if (index != _previousPageIndex) {
- if ([_delegate respondsToSelector:@selector(photoBrowser:didDisplayPhotoAtIndex:)])
- [_delegate photoBrowser:self didDisplayPhotoAtIndex:index];
- _previousPageIndex = index;
- }
-
- // Update nav
- [self updateNavigation];
-
- }
- #pragma mark - Frame Calculations
- - (CGRect)frameForPagingScrollView {
- CGRect frame = self.view.bounds;// [[UIScreen mainScreen] bounds];
- frame.origin.x -= PADDING;
- frame.size.width += (2 * PADDING);
- return CGRectIntegral(frame);
- }
- - (CGRect)frameForPageAtIndex:(NSUInteger)index {
- // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in
- // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's
- // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape
- // because it has a rotation transform applied.
- CGRect bounds = _pagingScrollView.bounds;
- CGRect pageFrame = bounds;
- pageFrame.size.width -= (2 * PADDING);
- pageFrame.origin.x = (bounds.size.width * index) + PADDING;
- return CGRectIntegral(pageFrame);
- }
- - (CGSize)contentSizeForPagingScrollView {
- // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
- CGRect bounds = _pagingScrollView.bounds;
- return CGSizeMake(bounds.size.width * [self numberOfPhotos], bounds.size.height);
- }
- - (CGPoint)contentOffsetForPageAtIndex:(NSUInteger)index {
- CGFloat pageWidth = _pagingScrollView.bounds.size.width;
- CGFloat newOffset = index * pageWidth;
- return CGPointMake(newOffset, 0);
- }
- - (CGRect)frameForToolbarAtOrientation:(UIInterfaceOrientation)orientation {
- CGFloat height = 44;
- if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone &&
- UIInterfaceOrientationIsLandscape(orientation)) height = 32;
- return CGRectIntegral(CGRectMake(0, self.view.bounds.size.height - height, self.view.bounds.size.width, height));
- }
- - (CGRect)frameForCaptionView:(MWCaptionView *)captionView atIndex:(NSUInteger)index {
- CGRect pageFrame = [self frameForPageAtIndex:index];
- CGSize captionSize = [captionView sizeThatFits:CGSizeMake(pageFrame.size.width, 0)];
- CGRect captionFrame = CGRectMake(pageFrame.origin.x,
- pageFrame.size.height - captionSize.height - (_toolbar.superview?_toolbar.frame.size.height:0),
- pageFrame.size.width,
- captionSize.height);
- return CGRectIntegral(captionFrame);
- }
- - (CGRect)frameForSelectedButton:(UIButton *)selectedButton atIndex:(NSUInteger)index {
- CGRect pageFrame = [self frameForPageAtIndex:index];
- CGFloat yOffset = 0;
- if (![self areControlsHidden]) {
- UINavigationBar *navBar = self.navigationController.navigationBar;
- yOffset = navBar.frame.origin.y + navBar.frame.size.height;
- }
- CGFloat statusBarOffset = [[UIApplication sharedApplication] statusBarFrame].size.height;
- #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
- if (SYSTEM_VERSION_LESS_THAN(@"7") && !self.wantsFullScreenLayout) statusBarOffset = 0;
- #endif
- CGRect captionFrame = CGRectMake(pageFrame.origin.x + pageFrame.size.width - 20 - selectedButton.frame.size.width,
- statusBarOffset + yOffset,
- selectedButton.frame.size.width,
- selectedButton.frame.size.height);
- return CGRectIntegral(captionFrame);
- }
- #pragma mark - UIScrollView Delegate
- - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
-
- // Checks
- if (!_viewIsActive || _performingLayout || _rotating) return;
-
- // Tile pages
- [self tilePages];
-
- // Calculate current page
- CGRect visibleBounds = _pagingScrollView.bounds;
- NSInteger index = (NSInteger)(floorf(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds)));
- if (index < 0) index = 0;
- if (index > [self numberOfPhotos] - 1) index = [self numberOfPhotos] - 1;
- NSUInteger previousCurrentPage = _currentPageIndex;
- _currentPageIndex = index;
- if (_currentPageIndex != previousCurrentPage) {
- [self didStartViewingPageAtIndex:index];
- }
-
- }
- - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
- // Hide controls when dragging begins
- [self setControlsHidden:YES animated:YES permanent:NO];
- }
- - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
- // Update nav when page changes
- [self updateNavigation];
- }
- #pragma mark - Navigation
- - (void)updateNavigation {
-
- // Title
- NSUInteger numberOfPhotos = [self numberOfPhotos];
- if (_gridController) {
- if (_gridController.selectionMode) {
- self.title = NSEaseLocalizedString(@"Select Photos", nil);
- } else {
- NSString *photosText;
- if (numberOfPhotos == 1) {
- photosText = NSEaseLocalizedString(@"photo", @"Used in the context: '1 photo'");
- } else {
- photosText = NSEaseLocalizedString(@"photos", @"Used in the context: '3 photos'");
- }
- self.title = [NSString stringWithFormat:@"%lu %@", (unsigned long)numberOfPhotos, photosText];
- }
- } else if (numberOfPhotos > 1) {
- if ([_delegate respondsToSelector:@selector(photoBrowser:titleForPhotoAtIndex:)]) {
- self.title = [_delegate photoBrowser:self titleForPhotoAtIndex:_currentPageIndex];
- } else {
- self.title = [NSString stringWithFormat:@"%lu %@ %lu", (unsigned long)(_currentPageIndex+1), NSEaseLocalizedString(@"of", @"Used in the context: 'Showing 1 of 3 items'"), (unsigned long)numberOfPhotos];
- }
- } else {
- self.title = nil;
- }
-
- // Buttons
- _previousButton.enabled = (_currentPageIndex > 0);
- _nextButton.enabled = (_currentPageIndex < numberOfPhotos - 1);
- _actionButton.enabled = [[self photoAtIndex:_currentPageIndex] underlyingImage] != nil;
-
- }
- - (void)jumpToPageAtIndex:(NSUInteger)index animated:(BOOL)animated {
-
- // Change page
- if (index < [self numberOfPhotos]) {
- CGRect pageFrame = [self frameForPageAtIndex:index];
- [_pagingScrollView setContentOffset:CGPointMake(pageFrame.origin.x - PADDING, 0) animated:animated];
- [self updateNavigation];
- }
-
- // Update timer to give more time
- [self hideControlsAfterDelay];
-
- }
- - (void)gotoPreviousPage {
- [self showPreviousPhotoAnimated:NO];
- }
- - (void)gotoNextPage {
- [self showNextPhotoAnimated:NO];
- }
- - (void)showPreviousPhotoAnimated:(BOOL)animated {
- [self jumpToPageAtIndex:_currentPageIndex-1 animated:animated];
- }
- - (void)showNextPhotoAnimated:(BOOL)animated {
- [self jumpToPageAtIndex:_currentPageIndex+1 animated:animated];
- }
- #pragma mark - Interactions
- - (void)selectedButtonTapped:(id)sender {
- UIButton *selectedButton = (UIButton *)sender;
- selectedButton.selected = !selectedButton.selected;
- NSUInteger index = NSUIntegerMax;
- for (MWZoomingScrollView *page in _visiblePages) {
- if (page.selectedButton == selectedButton) {
- index = page.index;
- break;
- }
- }
- if (index != NSUIntegerMax) {
- [self setPhotoSelected:selectedButton.selected atIndex:index];
- }
- }
- #pragma mark - Grid
- - (void)showGridAnimated {
- [self showGrid:YES];
- }
- - (void)showGrid:(BOOL)animated {
- if (_gridController) return;
-
- // Init grid controller
- _gridController = [[MWGridViewController alloc] init];
- _gridController.initialContentOffset = _currentGridContentOffset;
- _gridController.browser = self;
- _gridController.selectionMode = _displaySelectionButtons;
- _gridController.view.frame = self.view.bounds;
- _gridController.view.frame = CGRectOffset(_gridController.view.frame, 0, (self.startOnGrid ? -1 : 1) * self.view.bounds.size.height);
- // Stop specific layout being triggered
- _skipNextPagingScrollViewPositioning = YES;
-
- // Add as a child view controller
- [self addChildViewController:_gridController];
- [self.view addSubview:_gridController.view];
-
- // Hide action button on nav bar if it exists
- if (self.navigationItem.rightBarButtonItem == _actionButton) {
- _gridPreviousRightNavItem = _actionButton;
- [self.navigationItem setRightBarButtonItem:nil animated:YES];
- } else {
- _gridPreviousRightNavItem = nil;
- }
-
- // Update
- [self updateNavigation];
- [self setControlsHidden:NO animated:YES permanent:YES];
-
- // Animate grid in and photo scroller out
- [UIView animateWithDuration:animated ? 0.3 : 0 animations:^(void) {
- self->_gridController.view.frame = self.view.bounds;
- CGRect newPagingFrame = [self frameForPagingScrollView];
- newPagingFrame = CGRectOffset(newPagingFrame, 0, (self.startOnGrid ? 1 : -1) * newPagingFrame.size.height);
- self->_pagingScrollView.frame = newPagingFrame;
- } completion:^(BOOL finished) {
- [self->_gridController didMoveToParentViewController:self];
- }];
-
- }
- - (void)hideGrid {
-
- if (!_gridController) return;
-
- // Remember previous content offset
- _currentGridContentOffset = _gridController.collectionView.contentOffset;
-
- // Restore action button if it was removed
- if (_gridPreviousRightNavItem == _actionButton && _actionButton) {
- [self.navigationItem setRightBarButtonItem:_gridPreviousRightNavItem animated:YES];
- }
-
- // Position prior to hide animation
- CGRect newPagingFrame = [self frameForPagingScrollView];
- newPagingFrame = CGRectOffset(newPagingFrame, 0, (self.startOnGrid ? 1 : -1) * newPagingFrame.size.height);
- _pagingScrollView.frame = newPagingFrame;
-
- // Remember and remove controller now so things can detect a nil grid controller
- MWGridViewController *tmpGridController = _gridController;
- _gridController = nil;
-
- // Update
- [self updateNavigation];
- [self updateVisiblePageStates];
-
- // Animate, hide grid and show paging scroll view
- [UIView animateWithDuration:0.3 animations:^{
- tmpGridController.view.frame = CGRectOffset(self.view.bounds, 0, (self.startOnGrid ? -1 : 1) * self.view.bounds.size.height);
- self->_pagingScrollView.frame = [self frameForPagingScrollView];
- } completion:^(BOOL finished) {
- [tmpGridController willMoveToParentViewController:nil];
- [tmpGridController.view removeFromSuperview];
- [tmpGridController removeFromParentViewController];
- [self setControlsHidden:NO animated:YES permanent:NO]; // retrigger timer
- }];
- }
- #pragma mark - Control Hiding / Showing
- // If permanent then we don't set timers to hide again
- // Fades all controls on iOS 5 & 6, and iOS 7 controls slide and fade
- - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated permanent:(BOOL)permanent {
-
- // Force visible
- if (![self numberOfPhotos] || _gridController || _alwaysShowControls)
- hidden = NO;
-
- // Cancel any timers
- [self cancelControlHiding];
-
- // Animations & positions
- BOOL slideAndFade = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7");
- CGFloat animatonOffset = 20;
- CGFloat animationDuration = (animated ? 0.35 : 0);
-
- // Status bar
- if (!_leaveStatusBarAlone) {
- if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
-
- // iOS 7
- // Hide status bar
- if (!_isVCBasedStatusBarAppearance) {
-
- // Non-view controller based
- [[UIApplication sharedApplication] setStatusBarHidden:hidden withAnimation:animated ? UIStatusBarAnimationSlide : UIStatusBarAnimationNone];
-
- } else {
-
- // View controller based so animate away
- _statusBarShouldBeHidden = hidden;
- [UIView animateWithDuration:animationDuration animations:^(void) {
- [self setNeedsStatusBarAppearanceUpdate];
- } completion:^(BOOL finished) {}];
-
- }
- } else {
-
- // iOS < 7
- // Status bar and nav bar positioning
- BOOL fullScreen = YES;
- #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
- if (SYSTEM_VERSION_LESS_THAN(@"7")) fullScreen = self.wantsFullScreenLayout;
- #endif
- if (fullScreen) {
-
- // Need to get heights and set nav bar position to overcome display issues
-
- // Get status bar height if visible
- CGFloat statusBarHeight = 0;
- if (![UIApplication sharedApplication].statusBarHidden) {
- CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
- statusBarHeight = MIN(statusBarFrame.size.height, statusBarFrame.size.width);
- }
-
- // Status Bar
- [[UIApplication sharedApplication] setStatusBarHidden:hidden withAnimation:animated?UIStatusBarAnimationFade:UIStatusBarAnimationNone];
-
- // Get status bar height if visible
- if (![UIApplication sharedApplication].statusBarHidden) {
- CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
- statusBarHeight = MIN(statusBarFrame.size.height, statusBarFrame.size.width);
- }
-
- // Set navigation bar frame
- CGRect navBarFrame = self.navigationController.navigationBar.frame;
- navBarFrame.origin.y = statusBarHeight;
- self.navigationController.navigationBar.frame = navBarFrame;
-
- }
-
- }
- }
-
- // Toolbar, nav bar and captions
- // Pre-appear animation positions for iOS 7 sliding
- if (slideAndFade && [self areControlsHidden] && !hidden && animated) {
-
- // Toolbar
- _toolbar.frame = CGRectOffset([self frameForToolbarAtOrientation:self.interfaceOrientation], 0, animatonOffset);
-
- // Captions
- for (MWZoomingScrollView *page in _visiblePages) {
- if (page.captionView) {
- MWCaptionView *v = page.captionView;
- // Pass any index, all we're interested in is the Y
- CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
- captionFrame.origin.x = v.frame.origin.x; // Reset X
- v.frame = CGRectOffset(captionFrame, 0, animatonOffset);
- }
- }
-
- }
- [UIView animateWithDuration:animationDuration animations:^(void) {
-
- CGFloat alpha = hidden ? 0 : 1;
- // Nav bar slides up on it's own on iOS 7
- [self.navigationController.navigationBar setAlpha:alpha];
-
- // Toolbar
- if (slideAndFade) {
- self->_toolbar.frame = [self frameForToolbarAtOrientation:self.interfaceOrientation];
- if (hidden) self->_toolbar.frame = CGRectOffset(self->_toolbar.frame, 0, animatonOffset);
- }
- self->_toolbar.alpha = alpha;
- // Captions
- for (MWZoomingScrollView *page in self->_visiblePages) {
- if (page.captionView) {
- MWCaptionView *v = page.captionView;
- if (slideAndFade) {
- // Pass any index, all we're interested in is the Y
- CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
- captionFrame.origin.x = v.frame.origin.x; // Reset X
- if (hidden) captionFrame = CGRectOffset(captionFrame, 0, animatonOffset);
- v.frame = captionFrame;
- }
- v.alpha = alpha;
- }
- }
-
- // Selected buttons
- for (MWZoomingScrollView *page in self->_visiblePages) {
- if (page.selectedButton) {
- UIButton *v = page.selectedButton;
- CGRect newFrame = [self frameForSelectedButton:v atIndex:0];
- newFrame.origin.x = v.frame.origin.x;
- v.frame = newFrame;
- }
- }
- } completion:^(BOOL finished) {}];
-
- // Control hiding timer
- // Will cancel existing timer but only begin hiding if
- // they are visible
- if (!permanent) [self hideControlsAfterDelay];
-
- }
- - (BOOL)prefersStatusBarHidden {
- if (!_leaveStatusBarAlone) {
- return _statusBarShouldBeHidden;
- } else {
- return [self presentingViewControllerPrefersStatusBarHidden];
- }
- }
- - (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
- return UIStatusBarAnimationSlide;
- }
- - (void)cancelControlHiding {
- // If a timer exists then cancel and release
- if (_controlVisibilityTimer) {
- [_controlVisibilityTimer invalidate];
- _controlVisibilityTimer = nil;
- }
- }
- // Enable/disable control visiblity timer
- - (void)hideControlsAfterDelay {
- if (![self areControlsHidden]) {
- [self cancelControlHiding];
- _controlVisibilityTimer = [NSTimer scheduledTimerWithTimeInterval:self.delayToHideElements target:self selector:@selector(hideControls) userInfo:nil repeats:NO];
- }
- }
- - (BOOL)areControlsHidden { return (_toolbar.alpha == 0); }
- - (void)hideControls { [self setControlsHidden:YES animated:YES permanent:NO]; }
- - (void)toggleControls { [self setControlsHidden:![self areControlsHidden] animated:YES permanent:NO]; }
- #pragma mark - Properties
- // Handle depreciated method
- - (void)setInitialPageIndex:(NSUInteger)index {
- [self setCurrentPhotoIndex:index];
- }
- - (void)setCurrentPhotoIndex:(NSUInteger)index {
- // Validate
- NSUInteger photoCount = [self numberOfPhotos];
- if (photoCount == 0) {
- index = 0;
- } else {
- if (index >= photoCount)
- index = [self numberOfPhotos]-1;
- }
- _currentPageIndex = index;
- if ([self isViewLoaded]) {
- [self jumpToPageAtIndex:index animated:NO];
- if (!_viewIsActive)
- [self tilePages]; // Force tiling if view is not visible
- }
- }
- #pragma mark - Misc
- - (void)doneButtonPressed:(id)sender {
- // Only if we're modal and there's a done button
- if (_doneButton) {
- // See if we actually just want to show/hide grid
- if (self.enableGrid) {
- if (self.startOnGrid && !_gridController) {
- [self showGrid:YES];
- return;
- } else if (!self.startOnGrid && _gridController) {
- [self hideGrid];
- return;
- }
- }
- // Dismiss view controller
- if ([_delegate respondsToSelector:@selector(photoBrowserDidFinishModalPresentation:)]) {
- // Call delegate method and let them dismiss us
- [_delegate photoBrowserDidFinishModalPresentation:self];
- } else {
- [self dismissViewControllerAnimated:YES completion:nil];
- }
- }
- }
- #pragma mark - Actions
- - (void)actionButtonPressed:(id)sender {
- if (_actionsSheet) {
-
- // Dismiss
- [_actionsSheet dismissWithClickedButtonIndex:_actionsSheet.cancelButtonIndex animated:YES];
-
- } else {
-
- // Only react when image has loaded
- id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
- if ([self numberOfPhotos] > 0 && [photo underlyingImage]) {
-
- // If they have defined a delegate method then just message them
- if ([self.delegate respondsToSelector:@selector(photoBrowser:actionButtonPressedForPhotoAtIndex:)]) {
-
- // Let delegate handle things
- [self.delegate photoBrowser:self actionButtonPressedForPhotoAtIndex:_currentPageIndex];
-
- } else {
-
- // Handle default actions
- if (SYSTEM_VERSION_LESS_THAN(@"6")) {
-
- // Old handling of activities with action sheet
- if ([MFMailComposeViewController canSendMail]) {
- _actionsSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
- cancelButtonTitle:NSEaseLocalizedString(@"Cancel", nil) destructiveButtonTitle:nil
- otherButtonTitles:NSEaseLocalizedString(@"Save", nil), NSEaseLocalizedString(@"Copy", nil), NSEaseLocalizedString(@"Email", nil), nil];
- } else {
- _actionsSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
- cancelButtonTitle:NSEaseLocalizedString(@"Cancel", nil) destructiveButtonTitle:nil
- otherButtonTitles:NSEaseLocalizedString(@"Save", nil), NSEaseLocalizedString(@"Copy", nil), nil];
- }
- _actionsSheet.tag = ACTION_SHEET_OLD_ACTIONS;
- _actionsSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
- if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
- [_actionsSheet showFromBarButtonItem:sender animated:YES];
- } else {
- [_actionsSheet showInView:self.view];
- }
-
- } else {
-
- // Show activity view controller
- NSMutableArray *items = [NSMutableArray arrayWithObject:[photo underlyingImage]];
- if (photo.caption) {
- [items addObject:photo.caption];
- }
- self.activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
-
- // Show loading spinner after a couple of seconds
- double delayInSeconds = 2.0;
- dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
- dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
- if (self.activityViewController) {
- [self showProgressHUDWithMessage:nil];
- }
- });
- // Show
- typeof(self) __weak weakSelf = self;
- [self.activityViewController setCompletionHandler:^(NSString *activityType, BOOL completed) {
- weakSelf.activityViewController = nil;
- [weakSelf hideControlsAfterDelay];
- [weakSelf hideProgressHUD:YES];
- }];
- // iOS 8 - Set the Anchor Point for the popover
- if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8")) {
- self.activityViewController.popoverPresentationController.barButtonItem = _actionButton;
- }
- [self presentViewController:self.activityViewController animated:YES completion:nil];
-
- }
-
- }
-
- // Keep controls hidden
- [self setControlsHidden:NO animated:YES permanent:YES];
- }
- }
- }
- #pragma mark - Action Sheet Delegate
- - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
- if (actionSheet.tag == ACTION_SHEET_OLD_ACTIONS) {
- // Old Actions
- _actionsSheet = nil;
- if (buttonIndex != actionSheet.cancelButtonIndex) {
- if (buttonIndex == actionSheet.firstOtherButtonIndex) {
- [self savePhoto]; return;
- } else if (buttonIndex == actionSheet.firstOtherButtonIndex + 1) {
- [self copyPhoto]; return;
- } else if (buttonIndex == actionSheet.firstOtherButtonIndex + 2) {
- [self emailPhoto]; return;
- }
- }
- }
- [self hideControlsAfterDelay]; // Continue as normal...
- }
- #pragma mark - Action Progress
- - (MBProgressHUD *)progressHUD {
- if (!_progressHUD) {
- _progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
- _progressHUD.minSize = CGSizeMake(120, 120);
- _progressHUD.minShowTime = 1;
- // The sample image is based on the
- // work by: http://www.pixelpressicons.com
- // licence: http://creativecommons.org/licenses/by/2.5/ca/
- self.progressHUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MWPhotoBrowser.bundle/images/Checkmark.png"]];
- [self.view addSubview:_progressHUD];
- }
- return _progressHUD;
- }
- - (void)showProgressHUDWithMessage:(NSString *)message {
- self.progressHUD.labelText = message;
- self.progressHUD.mode = MBProgressHUDModeIndeterminate;
- [self.progressHUD show:YES];
- self.navigationController.navigationBar.userInteractionEnabled = NO;
- }
- - (void)hideProgressHUD:(BOOL)animated {
- [self.progressHUD hide:animated];
- self.navigationController.navigationBar.userInteractionEnabled = YES;
- }
- - (void)showProgressHUDCompleteMessage:(NSString *)message {
- if (message) {
- if (self.progressHUD.isHidden) [self.progressHUD show:YES];
- self.progressHUD.labelText = message;
- self.progressHUD.mode = MBProgressHUDModeCustomView;
- [self.progressHUD hide:YES afterDelay:1.5];
- } else {
- [self.progressHUD hide:YES];
- }
- self.navigationController.navigationBar.userInteractionEnabled = YES;
- }
- #pragma mark - Actions
- - (void)savePhoto {
- id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
- if ([photo underlyingImage]) {
- [self showProgressHUDWithMessage:[NSString stringWithFormat:@"%@\u2026" , NSEaseLocalizedString(@"Saving", @"Displayed with ellipsis as 'Saving...' when an item is in the process of being saved")]];
- [self performSelector:@selector(actuallySavePhoto:) withObject:photo afterDelay:0];
- }
- }
- - (void)actuallySavePhoto:(id<MWPhoto>)photo {
- if ([photo underlyingImage]) {
- UIImageWriteToSavedPhotosAlbum([photo underlyingImage], self,
- @selector(image:didFinishSavingWithError:contextInfo:), nil);
- }
- }
- - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
- [self showProgressHUDCompleteMessage: error ? NSEaseLocalizedString(@"Failed", @"Informing the user a process has failed") : NSEaseLocalizedString(@"Saved", @"Informing the user an item has been saved")];
- [self hideControlsAfterDelay]; // Continue as normal...
- }
- - (void)copyPhoto {
- id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
- if ([photo underlyingImage]) {
- [self showProgressHUDWithMessage:[NSString stringWithFormat:@"%@\u2026" , NSEaseLocalizedString(@"Copying", @"Displayed with ellipsis as 'Copying...' when an item is in the process of being copied")]];
- [self performSelector:@selector(actuallyCopyPhoto:) withObject:photo afterDelay:0];
- }
- }
- - (void)actuallyCopyPhoto:(id<MWPhoto>)photo {
- if ([photo underlyingImage]) {
- [[UIPasteboard generalPasteboard] setData:UIImagePNGRepresentation([photo underlyingImage])
- forPasteboardType:@"public.png"];
- [self showProgressHUDCompleteMessage:NSEaseLocalizedString(@"Copied", @"Informing the user an item has finished copying")];
- [self hideControlsAfterDelay]; // Continue as normal...
- }
- }
- - (void)emailPhoto {
- id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
- if ([photo underlyingImage]) {
- [self showProgressHUDWithMessage:[NSString stringWithFormat:@"%@\u2026" , NSEaseLocalizedString(@"Preparing", @"Displayed with ellipsis as 'Preparing...' when an item is in the process of being prepared")]];
- [self performSelector:@selector(actuallyEmailPhoto:) withObject:photo afterDelay:0];
- }
- }
- - (void)actuallyEmailPhoto:(id<MWPhoto>)photo {
- if ([photo underlyingImage]) {
- MFMailComposeViewController *emailer = [[MFMailComposeViewController alloc] init];
- emailer.mailComposeDelegate = self;
- [emailer setSubject:NSEaseLocalizedString(@"Photo", nil)];
- [emailer addAttachmentData:UIImagePNGRepresentation([photo underlyingImage]) mimeType:@"png" fileName:@"Photo.png"];
- if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
- emailer.modalPresentationStyle = UIModalPresentationPageSheet;
- }
- [self presentViewController:emailer animated:YES completion:nil];
- [self hideProgressHUD:NO];
- }
- }
- - (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
- if (result == MFMailComposeResultFailed) {
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSEaseLocalizedString(@"Email", nil)
- message:NSEaseLocalizedString(@"Email failed to send. Please try again.", nil)
- delegate:nil cancelButtonTitle:NSEaseLocalizedString(@"Dismiss", nil) otherButtonTitles:nil];
- [alert show];
- }
- [self dismissViewControllerAnimated:YES completion:nil];
- }
- @end
|