-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMVPagingScollView.m
executable file
·508 lines (410 loc) · 20 KB
/
MVPagingScollView.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//
// MVPagingScollView.m
// Field Guide 2010
//
// Created by Simon Sherrin on 25/01/11.
/*
Copyright (c) 2011 Museum Victoria
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*///
#import "MVPagingScollView.h"
#import "ImageScrollView.h"
#import "Image.h"
#include "TTTAttributedLabel.h"
@implementation MVPagingScollView
#define PAD 10
@synthesize images, scrollViewImageCredit, delegate, pagingScrollView, pageControl;
@synthesize scrollViewImageDescription = _scrollViewImageDescription;
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//If iPhone, move the credit and description label down 10
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
CGRect creditFrame = scrollViewImageCredit.frame;
creditFrame.origin.y = creditFrame.origin.y + 10;
scrollViewImageCredit.frame = creditFrame;
CGRect descriptionFrame = _scrollViewImageDescription.frame;
descriptionFrame.origin.y = descriptionFrame.origin.y + 10;
_scrollViewImageDescription.frame = descriptionFrame;
}
pagingScrollView.contentSize = [self contentSizeForPaging];
pagingScrollView.delegate = self;
UITapGestureRecognizer *singleFingerDTap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(handleDoubleTap:)];
singleFingerDTap.numberOfTapsRequired = 2;
[self.view addGestureRecognizer:singleFingerDTap];
[singleFingerDTap release];
UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(handleSingleTap:)];
singleFingerTap.numberOfTapsRequired = 1;
[singleFingerTap requireGestureRecognizerToFail:singleFingerDTap];
[self.view addGestureRecognizer:singleFingerTap];
[singleFingerTap release];
scrollViewImageCredit.text = @"New Text";
currentPages = [[NSMutableSet alloc] init];
queuedPages = [[NSMutableSet alloc] init];
NSLog(@"before tiling images");
[self tilePages];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSLog(@"pagingScrollVIew:viewWillAppear");
pagingScrollView.contentSize =[self contentSizeForPaging];
}
- (void)layoutSubviews
{
NSLog(@"MVPagingLayoutSubviews");
// [super layoutSubviews]; Commented out - shouldn't be called
}
-(void)newImageSet:(NSArray *)newImages{
NSLog(@"New Images Set");
self.images = newImages;
pageControl.numberOfPages = [self.images count];
pagingScrollView.contentSize = [self contentSizeForPaging];
[self setImageCredit:(Image*)[self.images objectAtIndex:0]];
//Remove Current Pages From display
for (ImageScrollView *page in currentPages) {
[queuedPages addObject:page];
[page removeFromSuperview];
}
[currentPages minusSet:queuedPages];
//Scroll to page
[pagingScrollView scrollRectToVisible:[self frameForPageAtIndex:0] animated:YES];
[self tilePages];
}
-(void) setImageCredit:(Image*)currentImage{
if (currentImage !=nil) {
_labelBackgroundView.hidden = YES;
self.scrollViewImageCredit.text = [NSString stringWithFormat:NSLocalizedString(@"Credit: %@",nil), [currentImage credit]];
self.scrollViewImageDescription.text = currentImage.imageDescription;
if (CGRectIsEmpty(initialImageDescriptionOrigin)) {
initialImageDescriptionOrigin = _scrollViewImageDescription.frame;
}
// the following snippet sets up the Scientific name within the <em></em> tags
// as italic.
if (currentImage.imageDescription.length > 0) {
CGRect labelFrame;
CGRect bounds = self.view.bounds;
if (_scrollViewImageDescription.frame.size.width > bounds.size.width) {
labelFrame = _scrollViewImageDescription.frame;
labelFrame.size.width = bounds.size.width - PAD;
_scrollViewImageDescription.frame = labelFrame;
}
NSString *text = currentImage.imageDescription;
UIFont *italicSystemFont = [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:12];
[_scrollViewImageDescription setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange theRange1 = [currentImage.imageDescription rangeOfString:@"<em>"];
NSRange theRange2 = [currentImage.imageDescription rangeOfString:@"</em>"];
NSRange theRange = NSUnionRange(theRange1, theRange2);
// Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
//UIFont *italicSystemFont = [UIFont italicSystemFontOfSize:13];
CTFontRef italicFont = CTFontCreateWithName((CFStringRef)italicSystemFont.fontName, italicSystemFont.pointSize, NULL);
if (italicFont) {
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(id)italicFont range:theRange];
CFRelease(italicFont);
}
[mutableAttributedString replaceCharactersInRange:theRange2 withString:@""];
[mutableAttributedString replaceCharactersInRange:theRange1 withString:@""];
return mutableAttributedString;
}];
bool hasMultipleLines = FALSE;
CGSize textsize = [_scrollViewImageDescription.text sizeWithFont:italicSystemFont];
labelFrame = _scrollViewImageDescription.frame;
if (textsize.width > labelFrame.size.width) {
if (UIUserInterfaceIdiomPad) {
labelFrame.origin.y = scrollViewImageCredit.frame.origin.y-PAD;
} else {
labelFrame.origin.y = scrollViewImageCredit.frame.origin.y;
}
labelFrame.size.height = textsize.height * 3;
_scrollViewImageDescription.numberOfLines = 0;
_scrollViewImageDescription.lineBreakMode = UILineBreakModeWordWrap;
_scrollViewImageDescription.frame = labelFrame;
hasMultipleLines = true;
} else {
initialImageDescriptionOrigin.origin.y = scrollViewImageCredit.frame.origin.y;
_scrollViewImageDescription.frame = initialImageDescriptionOrigin;
}
if (_scrollViewImageDescription.frame.size.width >= bounds.size.width || _scrollViewImageDescription.frame.size.width == (bounds.size.width-PAD)) {
labelFrame = _scrollViewImageDescription.frame;
//labelFrame.origin.x = 0;
if (hasMultipleLines) {
labelFrame.origin.y = _scrollViewImageDescription.frame.origin.y - (labelFrame.size.height-PAD); // 7 so that the caption label and pageControl/Credit label don't overlap displaying a black line
} else {
labelFrame.origin.y = _scrollViewImageDescription.frame.origin.y - (labelFrame.size.height);
}
_scrollViewImageDescription.frame = labelFrame;
_labelBackgroundView.hidden = NO;
// _scrollViewImageDescription.backgroundColor = pageControl.backgroundColor;
// _scrollViewImageDescription.backgroundColor = [UIColor clearColor];
// NSLog(@"pageControl.backgroundColor.1: %@", pageControl.backgroundColor);
// CGRect backgroundframe = CGRectMake(0, labelFrame.origin.y, labelFrame.size.width, labelFrame.size.height);
// UIView *backgroundView = [[UIView alloc] initWithFrame:backgroundframe];
// backgroundView.backgroundColor = pageControl.backgroundColor;
// backgroundView.alpha = pageControl.alpha;
// //backgroundView.opaque = FALSE;
//
// NSLog(@"pageControl.backgroundColor: %@", pageControl.backgroundColor);
// NSLog(@"backgroundView.backgroundColor: %@", backgroundView.backgroundColor);
//
// [self.view insertSubview:backgroundView belowSubview:_scrollViewImageDescription];
//
// [backgroundView release];
}
hasMultipleLines = FALSE;
}
}
}
- (CGRect) frameForPageAtIndex:(NSUInteger) index{
CGRect bounds = self.view.bounds;
CGRect pageFrame = bounds;
pageFrame.size.width -= ( 2* PAD);
pageFrame.origin.x = (bounds.size.width * index) + PAD;
return pageFrame;
}
- (CGSize) contentSizeForPaging{
CGRect bounds = pagingScrollView.bounds;
return CGSizeMake(bounds.size.width * [self.images count], bounds.size.height);
}
- (CGRect) frameSizeForPaging{
CGRect parentFrame = self.view.bounds;
parentFrame.origin.x -= PAD;
parentFrame.size.width += (2 * PAD );
return parentFrame;
}
-(UIImage *) imageAtIndex:(NSUInteger)index{
NSLog(@"imageAtIndex:%d", index);
Image *currentImage = (Image *) [self.images objectAtIndex:index];
NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@",[[currentImage filename] stringByDeletingPathExtension]] ofType:@"jpg"];
NSLog(@"imagepath:%@", path);
return [UIImage imageWithContentsOfFile:path];
}
- (NSData *) dataForImageAtIndex:(NSUInteger)index{
Image *currentImage = (Image *) [self.images objectAtIndex:index];
NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@",[[currentImage filename] stringByDeletingPathExtension]] ofType:@"jpg"];
return [NSData dataWithContentsOfFile:path];
}
- (void)configurePage:(ImageScrollView *)page forIndex:(NSUInteger)index
{
NSLog(@"ConfigurePage");
//page.delegate = self;
page.index = index;
page.frame = [self frameForPageAtIndex:index];
[page displayImage:[self imageAtIndex:index]];
// trial async code
/*
Image *currentImage = (Image *) [self.images objectAtIndex:index];
NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@",[[currentImage filename] stringByDeletingPathExtension]] ofType:@"jpg"];
dispatch_queue_t imageLoadQueue = dispatch_queue_create("imageLoading", NULL);
dispatch_async(imageLoadQueue, ^{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSData *imageData = [NSData dataWithContentsOfFile:path];
UIImage *tmpImage = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
[page displayImage:tmpImage];
});
[pool drain];
});
dispatch_release(imageLoadQueue);
*/
}
- (IBAction)changePage:(id)sender{
int page = pageControl.currentPage;
changedByPageControl = YES;
[self setImageCredit:(Image*)[self.images objectAtIndex:page]];
//Need to move scroll view to page X
[pagingScrollView scrollRectToVisible:[self frameForPageAtIndex:page] animated:YES];
}
- (void)tilePages
{
// Calculate which pages are visible
CGRect visibleBounds = pagingScrollView.bounds;
/* 27/02 */
int firstNeededPageIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds)); //added -1 to get the image offscreen on the left added
int lastNeededPageIndex = floorf((CGRectGetMaxX(visibleBounds)-1) / CGRectGetWidth(visibleBounds)); //added + 1 to get the image offscreen to the right added
firstNeededPageIndex = MAX(firstNeededPageIndex, 0);
lastNeededPageIndex = MIN(lastNeededPageIndex, [self.images count] - 1);
//load all images
//int firstNeededPageIndex = 0;
//int lastNeededPageIndex = [self.images count]-1;
// NSLog(@"first page:%d", firstNeededPageIndex);
// NSLog(@"lastPageindex:%d", lastNeededPageIndex);
// Recycle no-longer-visible pages
for (ImageScrollView *page in currentPages) {
if (page.index < firstNeededPageIndex || page.index > lastNeededPageIndex) {
[queuedPages addObject:page];
[page removeFromSuperview];
}
}
[currentPages minusSet:queuedPages];
// add missing pages
for (int index = firstNeededPageIndex; index <= lastNeededPageIndex; index++) {
if (![self isDisplayingPageForIndex:index]) {
ImageScrollView *page = [self dequeueRecycledPage];
if (page == nil) {
page = [[[ImageScrollView alloc] init] autorelease];
}
[self configurePage:page forIndex:index];
[pagingScrollView addSubview:page];
page.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
[currentPages addObject:page];
}
}
if (changedByPageControl) {
// do nothing - the scroll was initiated from the page control, not the user dragging
}else {
CGFloat pageWidth = pagingScrollView.bounds.size.width;
int currentpage = floor((pagingScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
if (currentpage >= 0 && currentpage <= ([self.images count]-1) ) //avoid trying to call outside the range of the array.
{
pageControl.currentPage = currentpage;
[self setImageCredit:(Image*)[self.images objectAtIndex:currentpage]];
}
}
}
// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
changedByPageControl = NO;
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
changedByPageControl = NO;
}
- (ImageScrollView *)dequeueRecycledPage
{
ImageScrollView *page = [queuedPages anyObject];
if (page) {
[[page retain] autorelease];
[queuedPages removeObject:page];
}
return page;
}
- (BOOL)isDisplayingPageForIndex:(NSUInteger)index
{
BOOL foundPage = NO;
for (ImageScrollView *page in currentPages) {
if (page.index == index) {
foundPage = YES;
break;
}
}
return foundPage;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self tilePages];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
return YES;
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
// here, our pagingScrollView bounds have not yet been updated for the new interface orientation. So this is a good
// place to calculate the content offset that we will need in the new orientation
CGFloat offset = pagingScrollView.contentOffset.x;
CGFloat pageWidth = pagingScrollView.bounds.size.width;
NSLog(@"MVPagingView:willRotateToInterfaceOrientation");
NSLog(@"contentOffset:%f ", offset);
if (offset >= 0) {
firstVisiblePageIndexBeforeRotation = floorf(offset / pageWidth);
percentScrolledIntoFirstVisiblePage = (offset - (firstVisiblePageIndexBeforeRotation * pageWidth)) / pageWidth;
} else {
firstVisiblePageIndexBeforeRotation = 0;
percentScrolledIntoFirstVisiblePage = offset / pageWidth;
}
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
// recalculate contentSize based on current orientation
pagingScrollView.contentSize = [self contentSizeForPaging];
NSLog(@"pagingScrollView.contentSize:%f,%f", pagingScrollView.contentSize.width, pagingScrollView.contentSize.height);
// adjust frames and configuration of each visible page
for (ImageScrollView *page in currentPages) {
CGPoint restorePoint = [page pointToCenterAfterRotation];
CGFloat restoreScale = [page scaleToRestoreAfterRotation];
page.frame = [self frameForPageAtIndex:page.index];
[page setMaxMinZoomScalesForCurrentBounds];
[page restoreCenterPoint:restorePoint scale:restoreScale];
}
// adjust contentOffset to preserve page location based on values collected prior to location
CGFloat pageWidth = pagingScrollView.bounds.size.width;
CGFloat newOffset = (firstVisiblePageIndexBeforeRotation * pageWidth) + (percentScrolledIntoFirstVisiblePage * pageWidth);
pagingScrollView.contentOffset = CGPointMake(newOffset, 0);
}
- (void)refreshLayout{
// Resizing isn't happing - probably due to layoutView on imageView;
// recalculate contentSize based on current orientation
//NSLog(@"Refresh View");
//int currentpage = pageControl.currentPage;
//NSLog(@"CurrentPage:%d", pageControl.currentPage);
//pagingScrollView.contentSize = [self contentSizeForPaging];
// [pagingScrollView scrollRectToVisible:[self frameForPageAtIndex:currentpage] animated:YES];
// adjust frames and configuration of each visible page
for (ImageScrollView *page in currentPages) {
CGPoint restorePoint = [page pointToCenterAfterRotation];
CGFloat restoreScale = [page scaleToRestoreAfterRotation];
/* [UIView animateWithDuration:1.0 animations:^{
page.frame = [self frameForPageAtIndex:page.index];
}];*/
[page setMaxMinZoomScalesForCurrentBounds];
[page restoreCenterPoint:restorePoint scale:restoreScale];
[page setZoomScale:(page.minimumZoomScale +0.1) animated:NO];
[page setZoomScale:page.minimumZoomScale animated:YES];
}
}
-(void) handleSingleTap:(UIGestureRecognizer *)sender{
//Pass to Parent - Needs to bubble up to top level
NSLog(@"MVPaging - HandleSingleTap");
if ([self.delegate respondsToSelector:@selector(handleSingleTap:)]) {
[self.delegate handleSingleTap:sender];
}
}
-(void) handleDoubleTap:(UIGestureRecognizer *)sender{
//Pass to Parent - Needs to bubble up to top level
NSLog(@"MVPaging - HandleDoubleTap");
// if ([self.delegate respondsToSelector:@selector(handleSingleTap:)]) {
// [self.delegate handleSingleTap:sender];
// }
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[self setLabelBackgroundView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.delegate = nil;
self.images = nil;
self.scrollViewImageCredit = nil;
self.pagingScrollView = nil;
self.pageControl = nil;
//currentPages = nil;
//queuedPages = nil;
}
- (void)dealloc {
[pagingScrollView release];
[pageControl release];
[images release];
[scrollViewImageCredit release];
[currentPages release];
[queuedPages release];
[_labelBackgroundView release];
[super dealloc];
}
@end