iOS模仿电子书首页实现书架布局样式
这篇文章主要为大家详细介绍了iOS实现类似电子书首页效果样式,实现书架布局样式,感兴趣的小伙伴们可以参考一下
本文实现了类似电子书首页,用来展示图书或小说的布局页面,书架列表【iPhone6模拟器】,屏幕尺寸还没进行适配,只是做个简单的demo【纯代码实现方式】
实现采用的是UICollectionView和UICollectionViewFlowLayout。关于UICollectionView的详细讲解请参考
一、实现layout的DecorationView
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 //
//FWBookShelfDecarationViewCollectionReusableView.h
//FWPersonalApp
//
//Createdbyhzkmnon16/2/18.
//Copyright?2016年ForrstWoo.Allrightsreserved.
//
#import
externNSIntegerconstkDecorationViewHeight;
@interfaceFWBookShelfDecarationView:UICollectionReusableView
@end 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 //
//FWBookShelfDecarationViewCollectionReusableView.m
//FWPersonalApp
//
//Createdbyhzkmnon16/2/18.
//Copyright?2016年ForrstWoo.Allrightsreserved.
//
#import"FWBookShelfDecarationView.h"
NSIntegerconstkDecorationViewHeight=216;
@implementationFWBookShelfDecarationView
-(instancetype)initWithFrame:(CGRect)frame
{
if(self=[superinitWithFrame:frame])
{
UIImageViewimg=[[UIImageViewalloc]initWithFrame:CGRectMake(0,0,screenSize.width,kDecorationViewHeight)];
img.image=[UIImageimageNamed:@"boolshelf.png"];
[selfaddSubview:img];
}
returnself;
}
@end FWBookShelfDecarationView类非常简单只是定义了Decarationview的背景图片,图上。
二、下载及导入可重新排序的第三方layout,用于我们移动图书后重新布局在实际项目中你或许会遇到在一个集合视图中移动一项到另外一个位置,那么此时我们需要对视图中的元素进行重新排序,今天推荐一个很好用的第三方类LXReorderableCollectionViewFlowLayout【点此链接进入GITHUB】
下面附上实现代码
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 //
//LXReorderableCollectionViewFlowLayout.h
//
//CreatedbyStanChangKhinBoonon1/10/12.
//Copyright(c)2012d--buzz.Allrightsreserved.
//
#import
@interfaceLXReorderableCollectionViewFlowLayout:UICollectionViewFlowLayout
@property(assign,nonatomic)CGFloatscrollingSpeed;
@property(assign,nonatomic)UIEdgeInsetsscrollingTriggerEdgeInsets;
@property(strong,nonatomic,readonly)UILongPressGestureRecognizerlongPressGestureRecognizer;
@property(strong,nonatomic,readonly)UIPanGestureRecognizerpanGestureRecognizer;
-(void)setUpGestureRecognizersOnCollectionView__attribute__((deprecated("CallstosetUpGestureRecognizersOnCollectionViewmethodarenotlongerneededassetuparedoneautomaticallythroughKVO.")));
@end
@protocolLXReorderableCollectionViewDataSource
@optional
-(void)collectionView:(UICollectionView)collectionViewitemAtIndexPath:(NSIndexPath)fromIndexPathwillMoveToIndexPath:(NSIndexPath)toIndexPath;
-(void)collectionView:(UICollectionView)collectionViewitemAtIndexPath:(NSIndexPath)fromIndexPathdidMoveToIndexPath:(NSIndexPath)toIndexPath;
-(BOOL)collectionView:(UICollectionView)collectionViewcanMoveItemAtIndexPath:(NSIndexPath)indexPath;
-(BOOL)collectionView:(UICollectionView)collectionViewitemAtIndexPath:(NSIndexPath)fromIndexPathcanMoveToIndexPath:(NSIndexPath)toIndexPath;
@end
@protocolLXReorderableCollectionViewDelegateFlowLayout
@optional
-(void)collectionView:(UICollectionView)collectionViewlayout:(UICollectionViewLayout)collectionViewLayoutwillBeginDraggingItemAtIndexPath:(NSIndexPath)indexPath;
-(void)collectionView:(UICollectionView)collectionViewlayout:(UICollectionViewLayout)collectionViewLayoutdidBeginDraggingItemAtIndexPath:(NSIndexPath)indexPath;
-(void)collectionView:(UICollectionView)collectionViewlayout:(UICollectionViewLayout)collectionViewLayoutwillEndDraggingItemAtIndexPath:(NSIndexPath)indexPath;
-(void)collectionView:(UICollectionView)collectionViewlayout:(UICollectionViewLayout)collectionViewLayoutdidEndDraggingItemAtIndexPath:(NSIndexPath)indexPath;
@end
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 //
//LXReorderableCollectionViewFlowLayout.m
//
//CreatedbyStanChangKhinBoonon1/10/12.
//Copyright(c)2012d--buzz.Allrightsreserved.
//
#import"LXReorderableCollectionViewFlowLayout.h"
#import
#import
#defineLX_FRAMES_PER_SECOND60.0
#ifndefCGGEOMETRY_LXSUPPORT_H_
CG_INLINECGPoint
LXS_CGPointAdd(CGPointpoint1,CGPointpoint2){
returnCGPointMake(point1.x+point2.x,point1.y+point2.y);
}
#endif
typedefNS_ENUM(NSInteger,LXScrollingDirection){
LXScrollingDirectionUnknown=0,
LXScrollingDirectionUp,
LXScrollingDirectionDown,
LXScrollingDirectionLeft,
LXScrollingDirectionRight
};
staticNSStringconstkLXScrollingDirectionKey=@"LXScrollingDirection";
staticNSStringconstkLXCollectionViewKeyPath=@"collectionView";
@interfaceCADisplayLink(LX_userInfo)
@property(nonatomic,copy)NSDictionaryLX_userInfo;
@end
@implementationCADisplayLink(LX_userInfo)
-(void)setLX_userInfo:(NSDictionary)LX_userInfo{
objc_setAssociatedObject(self,"LX_userInfo",LX_userInfo,OBJC_ASSOCIATION_COPY);
}
-(NSDictionary)LX_userInfo{
returnobjc_getAssociatedObject(self,"LX_userInfo");
}
@end
@interfaceUICollectionViewCell(LXReorderableCollectionViewFlowLayout)
-(UIImage)LX_rasterizedImage;
@end
@implementationUICollectionViewCell(LXReorderableCollectionViewFlowLayout)
-(UIImage)LX_rasterizedImage{
UIGraphicsBeginImageContextWithOptions(self.bounds.size,self.isOpaque,0.0f);
[self.layerrenderInContext:UIGraphicsGetCurrentContext()];
UIImageimage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnimage;
}
@end
@interfaceLXReorderableCollectionViewFlowLayout()
@property(strong,nonatomic)NSIndexPathselectedItemIndexPath;
@property(strong,nonatomic)UIViewcurrentView;
@property(assign,nonatomic)CGPointcurrentViewCenter;
@property(assign,nonatomic)CGPointpanTranslationInCollectionView;
@property(strong,nonatomic)CADisplayLinkdisplayLink;
@property(assign,nonatomic,readonly)iddataSource;
@property(assign,nonatomic,readonly)iddelegate;
@end
@implementationLXReorderableCollectionViewFlowLayout
-(void)setDefaults{
_scrollingSpeed=300.0f;
_scrollingTriggerEdgeInsets=UIEdgeInsetsMake(50.0f,50.0f,50.0f,50.0f);
}
-(void)setupCollectionView{
_longPressGestureRecognizer=[[UILongPressGestureRecognizeralloc]initWithTarget:self
action:@selector(handleLongPressGesture:)];
_longPressGestureRecognizer.delegate=self;
//Linksthedefaultlongpressgesturerecognizertothecustomlongpressgesturerecognizerwearecreatingnow
//byenforcingfailuredependencysothattheydoesn''tclash.
for(UIGestureRecognizergestureRecognizerinself.collectionView.gestureRecognizers){
if([gestureRecognizerisKindOfClass:[UILongPressGestureRecognizerclass]]){
[gestureRecognizerrequireGestureRecognizerToFail:_longPressGestureRecognizer];
}
}
[self.collectionViewaddGestureRecognizer:_longPressGestureRecognizer];
_panGestureRecognizer=[[UIPanGestureRecognizeralloc]initWithTarget:self
action:@selector(handlePanGesture:)];
_panGestureRecognizer.delegate=self;
[self.collectionViewaddGestureRecognizer:_panGestureRecognizer];
//Usefulinmultiplescenarios:onecommonscenariobeingwhentheNotificationCenterdrawerispulleddown
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleApplicationWillResignActive:)name:UIApplicationWillResignActiveNotificationobject:nil];
}
-(id)init{
self=[superinit];
if(self){
[selfsetDefaults];
[selfaddObserver:selfforKeyPath:kLXCollectionViewKeyPathoptions:NSKeyValueObservingOptionNewcontext:nil];
}
returnself;
}
-(id)initWithCoder:(NSCoder)aDecoder{
self=[superinitWithCoder:aDecoder];
if(self){
[selfsetDefaults];
[selfaddObserver:selfforKeyPath:kLXCollectionViewKeyPathoptions:NSKeyValueObservingOptionNewcontext:nil];
}
returnself;
}
-(void)dealloc{
[selfinvalidatesScrollTimer];
[selfremoveObserver:selfforKeyPath:kLXCollectionViewKeyPath];
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIApplicationWillResignActiveNotificationobject:nil];
}
-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes)layoutAttributes{
if([layoutAttributes.indexPathisEqual:self.selectedItemIndexPath]){
layoutAttributes.hidden=YES;
}
}
-(id)dataSource{
return(id)self.collectionView.dataSource;
}
-(id)delegate{
return(id)self.collectionView.delegate;
}
-(void)invalidateLayoutIfNecessary{
NSIndexPathnewIndexPath=[self.collectionViewindexPathForItemAtPoint:self.currentView.center];
NSIndexPathpreviousIndexPath=self.selectedItemIndexPath;
if((newIndexPath==nil)||[newIndexPathisEqual:previousIndexPath]){
return;
}
if([self.dataSourcerespondsToSelector:@selector(collectionView:itemAtIndexPath:canMoveToIndexPath:)]&&
![self.dataSourcecollectionView:self.collectionViewitemAtIndexPath:previousIndexPathcanMoveToIndexPath:newIndexPath]){
return;
}
self.selectedItemIndexPath=newIndexPath;
if([self.dataSourcerespondsToSelector:@selector(collectionView:itemAtIndexPath:willMoveToIndexPath:)]){
[self.dataSourcecollectionView:self.collectionViewitemAtIndexPath:previousIndexPathwillMoveToIndexPath:newIndexPath];
}
__weaktypeof(self)weakSelf=self;
[self.collectionViewperformBatchUpdates:^{
__strongtypeof(self)strongSelf=weakSelf;
if(strongSelf){
[strongSelf.collectionViewdeleteItemsAtIndexPaths:@[previousIndexPath]];
[strongSelf.collectionViewinsertItemsAtIndexPaths:@[newIndexPath]];
}
}completion:^(BOOLfinished){
__strongtypeof(self)strongSelf=weakSelf;
if([strongSelf.dataSourcerespondsToSelector:@selector(collectionView:itemAtIndexPath:didMoveToIndexPath:)]){
[strongSelf.dataSourcecollectionView:strongSelf.collectionViewitemAtIndexPath:previousIndexPathdidMoveToIndexPath:newIndexPath];
}
}];
}
-(void)invalidatesScrollTimer{
if(!self.displayLink.paused){
[self.displayLinkinvalidate];
}
self.displayLink=nil;
}
-(void)setupScrollTimerInDirection:(LXScrollingDirection)direction{
if(!self.displayLink.paused){
LXScrollingDirectionoldDirection=[self.displayLink.LX_userInfo[kLXScrollingDirectionKey]integerValue];
if(direction==oldDirection){
return;
}
}
[selfinvalidatesScrollTimer];
self.displayLink=[CADisplayLinkdisplayLinkWithTarget:selfselector:@selector(handleScroll:)];
self.displayLink.LX_userInfo=@{kLXScrollingDirectionKey:@(direction)};
[self.displayLinkaddToRunLoop:[NSRunLoopmainRunLoop]forMode:NSRunLoopCommonModes];
}
#pragmamark-Target/Actionmethods
//Tightloop,allocatememorysparely,eveniftheyarestackallocation.
-(void)handleScroll:(CADisplayLink)displayLink{
LXScrollingDirectiondirection=(LXScrollingDirection)[displayLink.LX_userInfo[kLXScrollingDirectionKey]integerValue];
if(direction==LXScrollingDirectionUnknown){
return;
}
CGSizeframeSize=self.collectionView.bounds.size;
CGSizecontentSize=self.collectionView.contentSize;
CGPointcontentOffset=self.collectionView.contentOffset;
UIEdgeInsetscontentInset=self.collectionView.contentInset;
//Importanttohaveaninteger`distance`asthe`contentOffset`propertyautomaticallygetsrounded
//anditwoulddivergefromtheview''scenterresultingina"cellisslippingawayunderfinger"-bug.
CGFloatdistance=rint(self.scrollingSpeed/LX_FRAMES_PER_SECOND);
CGPointtranslation=CGPointZero;
switch(direction){
caseLXScrollingDirectionUp:{
distance=-distance;
CGFloatminY=0.0f-contentInset.top;
if((contentOffset.y+distance)<=minY){
distance=-contentOffset.y-contentInset.top;
}
translation=CGPointMake(0.0f,distance);
}break;
caseLXScrollingDirectionDown:{
CGFloatmaxY=MAX(contentSize.height,frameSize.height)-frameSize.height+contentInset.bottom;
if((contentOffset.y+distance)>=maxY){
distance=maxY-contentOffset.y;
}
translation=CGPointMake(0.0f,distance);
}break;
caseLXScrollingDirectionLeft:{
distance=-distance;
CGFloatminX=0.0f-contentInset.left;
if((contentOffset.x+distance)<=minX){
distance=-contentOffset.x-contentInset.left;
}
translation=CGPointMake(distance,0.0f);
}break;
caseLXScrollingDirectionRight:{
CGFloatmaxX=MAX(contentSize.width,frameSize.width)-frameSize.width+contentInset.right;
if((contentOffset.x+distance)>=maxX){
distance=maxX-contentOffset.x;
}
translation=CGPointMake(distance,0.0f);
}break;
default:{
//Donothing...
}break;
}
self.currentViewCenter=LXS_CGPointAdd(self.currentViewCenter,translation);
self.currentView.center=LXS_CGPointAdd(self.currentViewCenter,self.panTranslationInCollectionView);
self.collectionView.contentOffset=LXS_CGPointAdd(contentOffset,translation);
}
-(void)handleLongPressGesture:(UILongPressGestureRecognizer)gestureRecognizer{
switch(gestureRecognizer.state){
caseUIGestureRecognizerStateBegan:{
NSIndexPathcurrentIndexPath=[self.collectionViewindexPathForItemAtPoint:[gestureRecognizerlocationInView:self.collectionView]];
if([self.dataSourcerespondsToSelector:@selector(collectionView:canMoveItemAtIndexPath:)]&&
![self.dataSourcecollectionView:self.collectionViewcanMoveItemAtIndexPath:currentIndexPath]){
return;
}
self.selectedItemIndexPath=currentIndexPath;
if([self.delegaterespondsToSelector:@selector(collectionView:layout:willBeginDraggingItemAtIndexPath:)]){
[self.delegatecollectionView:self.collectionViewlayout:selfwillBeginDraggingItemAtIndexPath:self.selectedItemIndexPath];
}
UICollectionViewCellcollectionViewCell=[self.collectionViewcellForItemAtIndexPath:self.selectedItemIndexPath];
self.currentView=[[UIViewalloc]initWithFrame:collectionViewCell.frame];
collectionViewCell.highlighted=YES;
UIImageViewhighlightedImageView=[[UIImageViewalloc]initWithImage:[collectionViewCellLX_rasterizedImage]];
highlightedImageView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
highlightedImageView.alpha=1.0f;
collectionViewCell.highlighted=NO;
UIImageViewimageView=[[UIImageViewalloc]initWithImage:[collectionViewCellLX_rasterizedImage]];
imageView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
imageView.alpha=0.0f;
[self.currentViewaddSubview:imageView];
[self.currentViewaddSubview:highlightedImageView];
[self.collectionViewaddSubview:self.currentView];
self.currentViewCenter=self.currentView.center;
__weaktypeof(self)weakSelf=self;
[UIView
animateWithDuration:0.3
delay:0.0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
__strongtypeof(self)strongSelf=weakSelf;
if(strongSelf){
strongSelf.currentView.transform=CGAffineTransformMakeScale(1.1f,1.1f);
highlightedImageView.alpha=0.0f;
imageView.alpha=1.0f;
}
}
completion:^(BOOLfinished){
__strongtypeof(self)strongSelf=weakSelf;
if(strongSelf){
[highlightedImageViewremoveFromSuperview];
if([strongSelf.delegaterespondsToSelector:@selector(collectionView:layout:didBeginDraggingItemAtIndexPath:)]){
[strongSelf.delegatecollectionView:strongSelf.collectionViewlayout:strongSelfdidBeginDraggingItemAtIndexPath:strongSelf.selectedItemIndexPath];
}
}
}];
[selfinvalidateLayout];
}break;
caseUIGestureRecognizerStateCancelled:
caseUIGestureRecognizerStateEnded:{
NSIndexPathcurrentIndexPath=self.selectedItemIndexPath;
if(currentIndexPath){
if([self.delegaterespondsToSelector:@selector(collectionView:layout:willEndDraggingItemAtIndexPath:)]){
[self.delegatecollectionView:self.collectionViewlayout:selfwillEndDraggingItemAtIndexPath:currentIndexPath];
}
self.selectedItemIndexPath=nil;
self.currentViewCenter=CGPointZero;
UICollectionViewLayoutAttributeslayoutAttributes=[selflayoutAttributesForItemAtIndexPath:currentIndexPath];
__weaktypeof(self)weakSelf=self;
[UIView
animateWithDuration:0.3
delay:0.0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
__strongtypeof(self)strongSelf=weakSelf;
if(strongSelf){
strongSelf.currentView.transform=CGAffineTransformMakeScale(1.0f,1.0f);
strongSelf.currentView.center=layoutAttributes.center;
}
}
completion:^(BOOLfinished){
__strongtypeof(self)strongSelf=weakSelf;
if(strongSelf){
[strongSelf.currentViewremoveFromSuperview];
strongSelf.currentView=nil;
[strongSelfinvalidateLayout];
if([strongSelf.delegaterespondsToSelector:@selector(collectionView:layout:didEndDraggingItemAtIndexPath:)]){
[strongSelf.delegatecollectionView:strongSelf.collectionViewlayout:strongSelfdidEndDraggingItemAtIndexPath:currentIndexPath];
}
}
}];
}
}break;
default:break;
}
}
-(void)handlePanGesture:(UIPanGestureRecognizer)gestureRecognizer{
switch(gestureRecognizer.state){
caseUIGestureRecognizerStateBegan:
caseUIGestureRecognizerStateChanged:{
self.panTranslationInCollectionView=[gestureRecognizertranslationInView:self.collectionView];
CGPointviewCenter=self.currentView.center=LXS_CGPointAdd(self.currentViewCenter,self.panTranslationInCollectionView);
[selfinvalidateLayoutIfNecessary];
switch(self.scrollDirection){
caseUICollectionViewScrollDirectionVertical:{
if(viewCenter.y<(CGRectGetMinY(self.collectionView.bounds)+self.scrollingTriggerEdgeInsets.top)){
[selfsetupScrollTimerInDirection:LXScrollingDirectionUp];
}else{
if(viewCenter.y>(CGRectGetMaxY(self.collectionView.bounds)-self.scrollingTriggerEdgeInsets.bottom)){
[selfsetupScrollTimerInDirection:LXScrollingDirectionDown];
}else{
[selfinvalidatesScrollTimer];
}
}
}break;
caseUICollectionViewScrollDirectionHorizontal:{
if(viewCenter.x<(CGRectGetMinX(self.collectionView.bounds)+self.scrollingTriggerEdgeInsets.left)){
[selfsetupScrollTimerInDirection:LXScrollingDirectionLeft];
}else{
if(viewCenter.x>(CGRectGetMaxX(self.collectionView.bounds)-self.scrollingTriggerEdgeInsets.right)){
[selfsetupScrollTimerInDirection:LXScrollingDirectionRight];
}else{
[selfinvalidatesScrollTimer];
}
}
}break;
}
}break;
caseUIGestureRecognizerStateCancelled:
caseUIGestureRecognizerStateEnded:{
[selfinvalidatesScrollTimer];
}break;
default:{
//Donothing...
}break;
}
}
#pragmamark-UICollectionViewLayoutoverriddenmethods
-(NSArray)layoutAttributesForElementsInRect:(CGRect)rect{
NSArraylayoutAttributesForElementsInRect=[superlayoutAttributesForElementsInRect:rect];
for(UICollectionViewLayoutAttributeslayoutAttributesinlayoutAttributesForElementsInRect){
switch(layoutAttributes.representedElementCategory){
caseUICollectionElementCategoryCell:{
[selfapplyLayoutAttributes:layoutAttributes];
}break;
default:{
//Donothing...
}break;
}
}
returnlayoutAttributesForElementsInRect;
}
-(UICollectionViewLayoutAttributes)layoutAttributesForItemAtIndexPath:(NSIndexPath)indexPath{
UICollectionViewLayoutAttributeslayoutAttributes=[superlayoutAttributesForItemAtIndexPath:indexPath];
switch(layoutAttributes.representedElementCategory){
caseUICollectionElementCategoryCell:{
[selfapplyLayoutAttributes:layoutAttributes];
}break;
default:{
//Donothing...
}break;
}
returnlayoutAttributes;
}
#pragmamark-UIGestureRecognizerDelegatemethods
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer)gestureRecognizer{
if([self.panGestureRecognizerisEqual:gestureRecognizer]){
return(self.selectedItemIndexPath!=nil);
}
returnYES;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer)gestureRecognizershouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer)otherGestureRecognizer{
if([self.longPressGestureRecognizerisEqual:gestureRecognizer]){
return[self.panGestureRecognizerisEqual:otherGestureRecognizer];
}
if([self.panGestureRecognizerisEqual:gestureRecognizer]){
return[self.longPressGestureRecognizerisEqual:otherGestureRecognizer];
}
returnNO;
}
#pragmamark-Key-ValueObservingmethods
-(void)observeValueForKeyPath:(NSString)keyPathofObject:(id)objectchange:(NSDictionary)changecontext:(void)context{
if([keyPathisEqualToString:kLXCollectionViewKeyPath]){
if(self.collectionView!=nil){
[selfsetupCollectionView];
}else{
[selfinvalidatesScrollTimer];
}
}
}
#pragmamark-Notifications
-(void)handleApplicationWillResignActive:(NSNotification)notification{
self.panGestureRecognizer.enabled=NO;
self.panGestureRecognizer.enabled=YES;
}
#pragmamark-Depreciatedmethods
#pragmamarkStartingfrom0.1.0
-(void)setUpGestureRecognizersOnCollectionView{
//Donothing...
}
@end 效果图:
三、实现自己的layout
首先继承LXReorderableCollectionViewFlowLayout,让该类具有重新排序功能。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 //
//FWBookshelfCollectionViewLayout.h
//FWPersonalApp
//
//Createdbyhzkmnon16/2/18.
//Copyright?2016年ForrstWoo.Allrightsreserved.
//
#import"LXReorderableCollectionViewFlowLayout.h"
externNSStringconstFWBookshelfCollectionViewLayoutDecorationViewKind;
@interfaceFWBookshelfCollectionViewLayout:LXReorderableCollectionViewFlowLayout
@end
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 //
//FWBookshelfCollectionViewLayout.m
//FWPersonalApp
//
//Createdbyhzkmnon16/2/18.
//Copyright?2016年ForrstWoo.Allrightsreserved.
//
#import"FWBookshelfCollectionViewLayout.h"
#import"FWBookShelfDecarationView.h"
NSStringconstFWBookshelfCollectionViewLayoutDecorationViewKind=@"FWBookshelfCollectionViewLayoutDecorationViewKind";
@interfaceFWBookshelfCollectionViewLayout()
@property(nonatomic,strong)NSDictionarybookShelfRectanges;
@propertyNSIntegercountOfRow;
@end
@implementationFWBookshelfCollectionVwww.hunanwang.netiewLayout
-(void)prepareLayout
{
[superprepareLayout];
[selfregisterClass:[FWBookShelfDecarationViewclass]forDecorationViewOfKind:FWBookshelfCollectionViewLayoutDecorationViewKind];
NSMutableDictionarydictionary=[NSMutableDictionarydictionary];
NSIntegeritemCount=[self.collectionViewnumberOfItemsInSection:0];
self.countOfRow=ceilf(itemCount/3.0);
for(introw=0;row {
dictionary[[NSIndexPathindexPathForItem:rowinSection:0]]=[NSValuevalueWithCGRect:CGRectMake(0,kDecorationViewHeightrow,screenSize.width,kDecorationViewHeight)];
}
self.bookShelfRectanges=[NSDictionarydictionaryWithDictionary:dictionary];
}
#pragmamarkRuntimeLayoutCalculations
-(NSArray)layoutAttributesForElementsInRect:(CGRect)rect
{
//callsupersoflowlayoutcanreturndefaultattributesforallcells,headers,andfooters
//NOTE:FlowlayouthasalreadytakencareoftheCellviewlayoutattributes!:)
NSArrayarray=[superlayoutAttributesForElementsInRect:rect];
//createamutablecopysowecanaddlayoutattributesforanyshelfsthat
//haveframesthatintersecttherecttheCollectionViewisinterestedin
NSMutableArraynewArray=[arraymutableCopy];
//NSLog(@"inrect:%@",NSStringFromCGRect(rect));
//Addanydecorationviews(shelves)who''srectintersectswiththe
//CGRectpassedtothelayoutbytheCollectionView
[self.bookShelfRectangesenumerateKeysAndObjectsUsingBlock:^(idkey,idshelfRect,BOOLstop){
//NSLog(@"[shelfRectCGRectValue]:%@",NSStringFromCGRect([shelfRectCGRectValue]));
if(CGRectIntersectsRect([shelfRectCGRectValue],rect))
{
UICollectionViewLayoutAttributesshelfAttributes=
[selflayoutAttributesForDecorationViewOfKind:FWBookshelfwww.visa158.comCollectionViewLayoutDecorationViewKind
atIndexPath:key];
[newArrayaddObject:shelfAttributes];
}
}];
for(inti=0;i<[self.collectionViewnumberOfItemsInSection:0];i++)
{
NSIndexPathindexPath=[NSIndexPathindexPathForItem:iinSection:0];
[newArrayaddObject:[selflayoutAttributesForItemAtIndexPath:indexPath]];
}
return[newArraycopy];
}
-(UICollectionViewLayoutAttributes)layoutAttributesForItemAtIndexPath:(NSIndexPath)indexPath
{
//NSLog(@"%@",NSStringFromCGSize([selfscreenSize]));375667
UICollectionViewLayoutAttributesattris=[UICollectionViewLayoutAttributeslayoutAttributesForCellWithIndexPath:indexPath];
NSIntegercurrentRow=indexPath.item/3;
CGRectframe=CGRectMake(20+(indexPath.item%3)(kCellWidth+17.5),35+currentRow(kCellHeight+65),kCellWidth,kCellHeight);
attris.frame=frame;
attris.zIndex=1;
returnattris;
}
-(UICollectionViewLayoutAttributes)layoutAttributesForDecorationViewOfKind:(NSString)decorationViewKindatIndexPath:(NSIndexPath)indexPath
{
idshelfRect=self.bookShelfRectanges[indexPath];
//thisshouldneverhappen,butjustincase...
if(!shelfRect)
returnnil;
UICollectionViewLayoutAttributesattributes=
[UICollectionViewLayoutAttributeslayoutAttributesForDecorationViewOfKind:decorationViewKind
withIndexPath:indexPath];
attributes.frame=[shelfRectCGRectValue];
//NSLog(@"UICollectionViewLayoutAttributes:.%@",NSStringFromCGRect([shelfRectCGRectValue]));
attributes.zIndex=-1;//shelvesgobehindotherviews
returnattributes;
}
-(CGSize)collectionViewContentSize
{
CGSizecontentSize=CGSizeMake(self.collectionView.bounds.size.width,self.countOfRowkDecorationViewHeight+20);
returncontentSize;
}
@end 四、应用
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 //
//FWAncientPoetryCollectionViewController.m
//FWPersonalApp
//
//Createdbyhzkmnon16/2/17.
//Copyright?2016年ForrstWoo.Allrightsreserved.
//
#import"FWAncientPoetryCollectionViewController.h"
#import"FWBookShelfDecarationView.h"
#import"FWBookshelfCollectionViewLayout.h"
#import"FWBookCategoryViewController.h"
@interfaceFWAncientPoetryCollectionViewController()
@property(nonatomic,strong)NSMutableArraybooks;
@end
@implementationFWAncientPoetryCollectionViewController
staticNSStringconstcellReuseIdentifier=@"Cell";
-(void)viewDidLoad{
[superviewDidLoad];
self.title=@"古籍";
self.collectionView.backgroundColor=[UIColorcolorWithPatternImage:[UIImageimageNamed:@"bookShelfBackground.png"]];
[self.collectionViewregisterClass:[UICollectionViewCellclass]forCellWithReuseIdentifier:cellReuseIdentifier];
self.books=[[NSMutableArrayalloc]initWithArray:[selfbookNameOfAllBooks]];
}
-(NSArray)bookNameOfAllBooks
{
return[[FWDataManagergetDataForPoetry]allKeys];
}
#pragmamark
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView)collectionView
{
return1;
}
-(NSInteger)collectionView:(UICollectionView)collectionViewnumberOfItemsInSection:(NSInteger)section
{
return[self.bookscount];
}
-(UICollectionViewCell)collectionView:(UICollectionView)collectionViewcellForItemAtIndexPath:(NSIndexPath)indexPath
{
UICollectionViewCellcell=[collectionViewdequeueReusableCellWithReuseIdentifier:cellReuseIdentifierforIndexPath:indexPath];
UIImageimage=[UIImageimageNamed:self.books[indexPath.item]];
cell.backgroundColor=[UIColorcolorWithPatternImage:image];
returncell;
}
-(void)collectionView:(UICollectionView)collectionViewitemAtIndexPath:(NSIndexPath)fromIndexPathwillMoveToIndexPath:(NSIndexPath)toIndexPath
{
NSStringtheBookName=self.books[fromIndexPath.item];
[self.booksremoveObjectAtIndex:fromIndexPath.item];
[self.booksinsertObject:theBookNameatIndex:toIndexPath.item];
}
#pragmamark-UICollectionViewDelegateFlowLayout
-(CGSize)collectionView:(UICollectionView)collectionViewlayout:(UICollectionViewLayout)collectionViewLayoutsizeForItemAtIndexPath:(NSIndexPath)indexPath
{
returnCGSizeMake(kCellWidth,kCellHeight);
}
-(void)collectionView:(UICollectionView)collectionViewdidSelectItemAtIndexPath:(NSIndexPath)indexPath
{
FWBookCategoryViewControllervc=[[FWBookCategoryViewControlleralloc]initWithUrlString:[[FWDataManagergetDataForPoetry]objectForKey:self.books[indexPath.item]]];
[self.navigationControllerpushViewController:vcanimated:YES];
}
-(void)didReceiveMemoryWarning{
[superdidReceiveMemoryWarning];
[self.booksremoveAllObjects];
self.books=nil;
}
@end
|
|