服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS模仿电子书首页实现书架布局样式

iOS模仿电子书首页实现书架布局样式

2021-01-09 17:30ForrestWoo IOS

这篇文章主要为大家详细介绍了iOS实现类似电子书首页效果样式,实现书架布局样式,感兴趣的小伙伴们可以参考一下

本文实现了类似电子书首页,用来展示图书或小说的布局页面,书架列表【iphone6模拟器】,屏幕尺寸还没进行适配,只是做个简单的demo【纯代码实现方式】

iOS模仿电子书首页实现书架布局样式

实现采用的是uicollectionview和uicollectionviewflowlayout。关于uicollectionview的详细讲解请参考

 iOS模仿电子书首页实现书架布局样式

一、实现layout的decorationview

iOS模仿电子书首页实现书架布局样式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//
// fwbookshelfdecarationviewcollectionreusableview.h
// fwpersonalapp
//
// created by hzkmn on 16/2/18.
// copyright © 2016年 forrstwoo. all rights reserved.
//
 
#import <uikit/uikit.h>
 
extern nsinteger const kdecorationviewheight;
 
 
@interface fwbookshelfdecarationview : 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
//
// created by hzkmn on 16/2/18.
// copyright © 2016年 forrstwoo. all rights reserved.
//
 
 
 
#import "fwbookshelfdecarationview.h"
 
nsinteger const kdecorationviewheight = 216;
 
@implementation fwbookshelfdecarationview
 
- (instancetype)initwithframe:(cgrect)frame
{
  if (self = [super initwithframe:frame])
  {
    uiimageview *img = [[uiimageview alloc] initwithframe:cgrectmake(0, 0, screensize.width, kdecorationviewheight)];
    img.image = [uiimage imagenamed:@"boolshelf.png"];
    [self addsubview:img];
  }
  
  return self;
}
@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
//
// created by stan chang khin boon on 1/10/12.
// copyright (c) 2012 d--buzz. all rights reserved.
//
 
#import <uikit/uikit.h>
 
@interface lxreorderablecollectionviewflowlayout : uicollectionviewflowlayout <uigesturerecognizerdelegate>
 
@property (assign, nonatomic) cgfloat scrollingspeed;
@property (assign, nonatomic) uiedgeinsets scrollingtriggeredgeinsets;
@property (strong, nonatomic, readonly) uilongpressgesturerecognizer *longpressgesturerecognizer;
@property (strong, nonatomic, readonly) uipangesturerecognizer *pangesturerecognizer;
 
- (void)setupgesturerecognizersoncollectionview __attribute__((deprecated("calls to setupgesturerecognizersoncollectionview method are not longer needed as setup are done automatically through kvo.")));
 
@end
 
@protocol lxreorderablecollectionviewdatasource <uicollectionviewdatasource>
 
@optional
 
- (void)collectionview:(uicollectionview *)collectionview itematindexpath:(nsindexpath *)fromindexpath willmovetoindexpath:(nsindexpath *)toindexpath;
- (void)collectionview:(uicollectionview *)collectionview itematindexpath:(nsindexpath *)fromindexpath didmovetoindexpath:(nsindexpath *)toindexpath;
 
- (bool)collectionview:(uicollectionview *)collectionview canmoveitematindexpath:(nsindexpath *)indexpath;
- (bool)collectionview:(uicollectionview *)collectionview itematindexpath:(nsindexpath *)fromindexpath canmovetoindexpath:(nsindexpath *)toindexpath;
 
@end
 
@protocol lxreorderablecollectionviewdelegateflowlayout <uicollectionviewdelegateflowlayout>
@optional
 
- (void)collectionview:(uicollectionview *)collectionview layout:(uicollectionviewlayout *)collectionviewlayout willbegindraggingitematindexpath:(nsindexpath *)indexpath;
- (void)collectionview:(uicollectionview *)collectionview layout:(uicollectionviewlayout *)collectionviewlayout didbegindraggingitematindexpath:(nsindexpath *)indexpath;
- (void)collectionview:(uicollectionview *)collectionview layout:(uicollectionviewlayout *)collectionviewlayout willenddraggingitematindexpath:(nsindexpath *)indexpath;
- (void)collectionview:(uicollectionview *)collectionview layout:(uicollectionviewlayout *)collectionviewlayout didenddraggingitematindexpath:(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
//
// created by stan chang khin boon on 1/10/12.
// copyright (c) 2012 d--buzz. all rights reserved.
//
 
#import "lxreorderablecollectionviewflowlayout.h"
#import <quartzcore/quartzcore.h>
#import <objc/runtime.h>
 
#define lx_frames_per_second 60.0
 
#ifndef cggeometry_lxsupport_h_
cg_inline cgpoint
lxs_cgpointadd(cgpoint point1, cgpoint point2) {
  return cgpointmake(point1.x + point2.x, point1.y + point2.y);
}
#endif
 
typedef ns_enum(nsinteger, lxscrollingdirection) {
  lxscrollingdirectionunknown = 0,
  lxscrollingdirectionup,
  lxscrollingdirectiondown,
  lxscrollingdirectionleft,
  lxscrollingdirectionright
};
 
static nsstring * const klxscrollingdirectionkey = @"lxscrollingdirection";
static nsstring * const klxcollectionviewkeypath = @"collectionview";
 
@interface cadisplaylink (lx_userinfo)
@property (nonatomic, copy) nsdictionary *lx_userinfo;
@end
 
@implementation cadisplaylink (lx_userinfo)
- (void) setlx_userinfo:(nsdictionary *) lx_userinfo {
  objc_setassociatedobject(self, "lx_userinfo", lx_userinfo, objc_association_copy);
}
 
- (nsdictionary *) lx_userinfo {
  return objc_getassociatedobject(self, "lx_userinfo");
}
@end
 
@interface uicollectionviewcell (lxreorderablecollectionviewflowlayout)
 
- (uiimage *)lx_rasterizedimage;
 
@end
 
@implementation uicollectionviewcell (lxreorderablecollectionviewflowlayout)
 
- (uiimage *)lx_rasterizedimage {
  uigraphicsbeginimagecontextwithoptions(self.bounds.size, self.isopaque, 0.0f);
  [self.layer renderincontext:uigraphicsgetcurrentcontext()];
  uiimage *image = uigraphicsgetimagefromcurrentimagecontext();
  uigraphicsendimagecontext();
  return image;
}
 
@end
 
@interface lxreorderablecollectionviewflowlayout ()
 
@property (strong, nonatomic) nsindexpath *selecteditemindexpath;
@property (strong, nonatomic) uiview *currentview;
@property (assign, nonatomic) cgpoint currentviewcenter;
@property (assign, nonatomic) cgpoint pantranslationincollectionview;
@property (strong, nonatomic) cadisplaylink *displaylink;
 
@property (assign, nonatomic, readonly) id<lxreorderablecollectionviewdatasource> datasource;
@property (assign, nonatomic, readonly) id<lxreorderablecollectionviewdelegateflowlayout> delegate;
 
@end
 
@implementation lxreorderablecollectionviewflowlayout
 
- (void)setdefaults {
  _scrollingspeed = 300.0f;
  _scrollingtriggeredgeinsets = uiedgeinsetsmake(50.0f, 50.0f, 50.0f, 50.0f);
}
 
- (void)setupcollectionview {
  _longpressgesturerecognizer = [[uilongpressgesturerecognizer alloc] initwithtarget:self
                                        action:@selector(handlelongpressgesture:)];
  _longpressgesturerecognizer.delegate = self;
  
  // links the default long press gesture recognizer to the custom long press gesture recognizer we are creating now
  // by enforcing failure dependency so that they doesn't clash.
  for (uigesturerecognizer *gesturerecognizer in self.collectionview.gesturerecognizers) {
    if ([gesturerecognizer iskindofclass:[uilongpressgesturerecognizer class]]) {
      [gesturerecognizer requiregesturerecognizertofail:_longpressgesturerecognizer];
    }
  }
  
  [self.collectionview addgesturerecognizer:_longpressgesturerecognizer];
  
  _pangesturerecognizer = [[uipangesturerecognizer alloc] initwithtarget:self
                                  action:@selector(handlepangesture:)];
  _pangesturerecognizer.delegate = self;
  [self.collectionview addgesturerecognizer:_pangesturerecognizer];
 
  // useful in multiple scenarios: one common scenario being when the notification center drawer is pulled down
  [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(handleapplicationwillresignactive:) name: uiapplicationwillresignactivenotification object:nil];
}
 
- (id)init {
  self = [super init];
  if (self) {
    [self setdefaults];
    [self addobserver:self forkeypath:klxcollectionviewkeypath options:nskeyvalueobservingoptionnew context:nil];
  }
  return self;
}
 
- (id)initwithcoder:(nscoder *)adecoder {
  self = [super initwithcoder:adecoder];
  if (self) {
    [self setdefaults];
    [self addobserver:self forkeypath:klxcollectionviewkeypath options:nskeyvalueobservingoptionnew context:nil];
  }
  return self;
}
 
- (void)dealloc {
  [self invalidatesscrolltimer];
  [self removeobserver:self forkeypath:klxcollectionviewkeypath];
  [[nsnotificationcenter defaultcenter] removeobserver:self name:uiapplicationwillresignactivenotification object:nil];
}
 
- (void)applylayoutattributes:(uicollectionviewlayoutattributes *)layoutattributes {
  if ([layoutattributes.indexpath isequal:self.selecteditemindexpath]) {
    layoutattributes.hidden = yes;
  }
}
 
- (id<lxreorderablecollectionviewdatasource>)datasource {
  return (id<lxreorderablecollectionviewdatasource>)self.collectionview.datasource;
}
 
- (id<lxreorderablecollectionviewdelegateflowlayout>)delegate {
  return (id<lxreorderablecollectionviewdelegateflowlayout>)self.collectionview.delegate;
}
 
- (void)invalidatelayoutifnecessary {
  nsindexpath *newindexpath = [self.collectionview indexpathforitematpoint:self.currentview.center];
  nsindexpath *previousindexpath = self.selecteditemindexpath;
  
  if ((newindexpath == nil) || [newindexpath isequal:previousindexpath]) {
    return;
  }
  
  if ([self.datasource respondstoselector:@selector(collectionview:itematindexpath:canmovetoindexpath:)] &&
    ![self.datasource collectionview:self.collectionview itematindexpath:previousindexpath canmovetoindexpath:newindexpath]) {
    return;
  }
  
  self.selecteditemindexpath = newindexpath;
  
  if ([self.datasource respondstoselector:@selector(collectionview:itematindexpath:willmovetoindexpath:)]) {
    [self.datasource collectionview:self.collectionview itematindexpath:previousindexpath willmovetoindexpath:newindexpath];
  }
 
  __weak typeof(self) weakself = self;
  [self.collectionview performbatchupdates:^{
    __strong typeof(self) strongself = weakself;
    if (strongself) {
      [strongself.collectionview deleteitemsatindexpaths:@[ previousindexpath ]];
      [strongself.collectionview insertitemsatindexpaths:@[ newindexpath ]];
    }
  } completion:^(bool finished) {
    __strong typeof(self) strongself = weakself;
    if ([strongself.datasource respondstoselector:@selector(collectionview:itematindexpath:didmovetoindexpath:)]) {
      [strongself.datasource collectionview:strongself.collectionview itematindexpath:previousindexpath didmovetoindexpath:newindexpath];
    }
  }];
}
 
- (void)invalidatesscrolltimer {
  if (!self.displaylink.paused) {
    [self.displaylink invalidate];
  }
  self.displaylink = nil;
}
 
- (void)setupscrolltimerindirection:(lxscrollingdirection)direction {
  if (!self.displaylink.paused) {
    lxscrollingdirection olddirection = [self.displaylink.lx_userinfo[klxscrollingdirectionkey] integervalue];
 
    if (direction == olddirection) {
      return;
    }
  }
  
  [self invalidatesscrolltimer];
 
  self.displaylink = [cadisplaylink displaylinkwithtarget:self selector:@selector(handlescroll:)];
  self.displaylink.lx_userinfo = @{ klxscrollingdirectionkey : @(direction) };
 
  [self.displaylink addtorunloop:[nsrunloop mainrunloop] formode:nsrunloopcommonmodes];
}
 
#pragma mark - target/action methods
 
// tight loop, allocate memory sparely, even if they are stack allocation.
- (void)handlescroll:(cadisplaylink *)displaylink {
  lxscrollingdirection direction = (lxscrollingdirection)[displaylink.lx_userinfo[klxscrollingdirectionkey] integervalue];
  if (direction == lxscrollingdirectionunknown) {
    return;
  }
  
  cgsize framesize = self.collectionview.bounds.size;
  cgsize contentsize = self.collectionview.contentsize;
  cgpoint contentoffset = self.collectionview.contentoffset;
  uiedgeinsets contentinset = self.collectionview.contentinset;
  // important to have an integer `distance` as the `contentoffset` property automatically gets rounded
  // and it would diverge from the view's center resulting in a "cell is slipping away under finger"-bug.
  cgfloat distance = rint(self.scrollingspeed / lx_frames_per_second);
  cgpoint translation = cgpointzero;
  
  switch(direction) {
    case lxscrollingdirectionup: {
      distance = -distance;
      cgfloat miny = 0.0f - contentinset.top;
      
      if ((contentoffset.y + distance) <= miny) {
        distance = -contentoffset.y - contentinset.top;
      }
      
      translation = cgpointmake(0.0f, distance);
    } break;
    case lxscrollingdirectiondown: {
      cgfloat maxy = max(contentsize.height, framesize.height) - framesize.height + contentinset.bottom;
      
      if ((contentoffset.y + distance) >= maxy) {
        distance = maxy - contentoffset.y;
      }
      
      translation = cgpointmake(0.0f, distance);
    } break;
    case lxscrollingdirectionleft: {
      distance = -distance;
      cgfloat minx = 0.0f - contentinset.left;
      
      if ((contentoffset.x + distance) <= minx) {
        distance = -contentoffset.x - contentinset.left;
      }
      
      translation = cgpointmake(distance, 0.0f);
    } break;
    case lxscrollingdirectionright: {
      cgfloat maxx = 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: {
      // do nothing...
    } 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) {
    case uigesturerecognizerstatebegan: {
      nsindexpath *currentindexpath = [self.collectionview indexpathforitematpoint:[gesturerecognizer locationinview:self.collectionview]];
      
      if ([self.datasource respondstoselector:@selector(collectionview:canmoveitematindexpath:)] &&
        ![self.datasource collectionview:self.collectionview canmoveitematindexpath:currentindexpath]) {
        return;
      }
      
      self.selecteditemindexpath = currentindexpath;
      
      if ([self.delegate respondstoselector:@selector(collectionview:layout:willbegindraggingitematindexpath:)]) {
        [self.delegate collectionview:self.collectionview layout:self willbegindraggingitematindexpath:self.selecteditemindexpath];
      }
      
      uicollectionviewcell *collectionviewcell = [self.collectionview cellforitematindexpath:self.selecteditemindexpath];
      
      self.currentview = [[uiview alloc] initwithframe:collectionviewcell.frame];
      
      collectionviewcell.highlighted = yes;
      uiimageview *highlightedimageview = [[uiimageview alloc] initwithimage:[collectionviewcell lx_rasterizedimage]];
      highlightedimageview.autoresizingmask = uiviewautoresizingflexiblewidth | uiviewautoresizingflexibleheight;
      highlightedimageview.alpha = 1.0f;
      
      collectionviewcell.highlighted = no;
      uiimageview *imageview = [[uiimageview alloc] initwithimage:[collectionviewcell lx_rasterizedimage]];
      imageview.autoresizingmask = uiviewautoresizingflexiblewidth | uiviewautoresizingflexibleheight;
      imageview.alpha = 0.0f;
      
      [self.currentview addsubview:imageview];
      [self.currentview addsubview:highlightedimageview];
      [self.collectionview addsubview:self.currentview];
      
      self.currentviewcenter = self.currentview.center;
      
      __weak typeof(self) weakself = self;
      [uiview
       animatewithduration:0.3
       delay:0.0
       options:uiviewanimationoptionbeginfromcurrentstate
       animations:^{
         __strong typeof(self) strongself = weakself;
         if (strongself) {
           strongself.currentview.transform = cgaffinetransformmakescale(1.1f, 1.1f);
           highlightedimageview.alpha = 0.0f;
           imageview.alpha = 1.0f;
         }
       }
       completion:^(bool finished) {
         __strong typeof(self) strongself = weakself;
         if (strongself) {
           [highlightedimageview removefromsuperview];
           
           if ([strongself.delegate respondstoselector:@selector(collectionview:layout:didbegindraggingitematindexpath:)]) {
             [strongself.delegate collectionview:strongself.collectionview layout:strongself didbegindraggingitematindexpath:strongself.selecteditemindexpath];
           }
         }
       }];
      
      [self invalidatelayout];
    } break;
    case uigesturerecognizerstatecancelled:
    case uigesturerecognizerstateended: {
      nsindexpath *currentindexpath = self.selecteditemindexpath;
      
      if (currentindexpath) {
        if ([self.delegate respondstoselector:@selector(collectionview:layout:willenddraggingitematindexpath:)]) {
          [self.delegate collectionview:self.collectionview layout:self willenddraggingitematindexpath:currentindexpath];
        }
        
        self.selecteditemindexpath = nil;
        self.currentviewcenter = cgpointzero;
        
        uicollectionviewlayoutattributes *layoutattributes = [self layoutattributesforitematindexpath:currentindexpath];
        
        __weak typeof(self) weakself = self;
        [uiview
         animatewithduration:0.3
         delay:0.0
         options:uiviewanimationoptionbeginfromcurrentstate
         animations:^{
           __strong typeof(self) strongself = weakself;
           if (strongself) {
             strongself.currentview.transform = cgaffinetransformmakescale(1.0f, 1.0f);
             strongself.currentview.center = layoutattributes.center;
           }
         }
         completion:^(bool finished) {
           __strong typeof(self) strongself = weakself;
           if (strongself) {
             [strongself.currentview removefromsuperview];
             strongself.currentview = nil;
             [strongself invalidatelayout];
             
             if ([strongself.delegate respondstoselector:@selector(collectionview:layout:didenddraggingitematindexpath:)]) {
               [strongself.delegate collectionview:strongself.collectionview layout:strongself didenddraggingitematindexpath:currentindexpath];
             }
           }
         }];
      }
    } break;
      
    default: break;
  }
}
 
- (void)handlepangesture:(uipangesturerecognizer *)gesturerecognizer {
  switch (gesturerecognizer.state) {
    case uigesturerecognizerstatebegan:
    case uigesturerecognizerstatechanged: {
      self.pantranslationincollectionview = [gesturerecognizer translationinview:self.collectionview];
      cgpoint viewcenter = self.currentview.center = lxs_cgpointadd(self.currentviewcenter, self.pantranslationincollectionview);
      
      [self invalidatelayoutifnecessary];
      
      switch (self.scrolldirection) {
        case uicollectionviewscrolldirectionvertical: {
          if (viewcenter.y < (cgrectgetminy(self.collectionview.bounds) + self.scrollingtriggeredgeinsets.top)) {
            [self setupscrolltimerindirection:lxscrollingdirectionup];
          } else {
            if (viewcenter.y > (cgrectgetmaxy(self.collectionview.bounds) - self.scrollingtriggeredgeinsets.bottom)) {
              [self setupscrolltimerindirection:lxscrollingdirectiondown];
            } else {
              [self invalidatesscrolltimer];
            }
          }
        } break;
        case uicollectionviewscrolldirectionhorizontal: {
          if (viewcenter.x < (cgrectgetminx(self.collectionview.bounds) + self.scrollingtriggeredgeinsets.left)) {
            [self setupscrolltimerindirection:lxscrollingdirectionleft];
          } else {
            if (viewcenter.x > (cgrectgetmaxx(self.collectionview.bounds) - self.scrollingtriggeredgeinsets.right)) {
              [self setupscrolltimerindirection:lxscrollingdirectionright];
            } else {
              [self invalidatesscrolltimer];
            }
          }
        } break;
      }
    } break;
    case uigesturerecognizerstatecancelled:
    case uigesturerecognizerstateended: {
      [self invalidatesscrolltimer];
    } break;
    default: {
      // do nothing...
    } break;
  }
}
 
#pragma mark - uicollectionviewlayout overridden methods
 
- (nsarray *)layoutattributesforelementsinrect:(cgrect)rect {
  nsarray *layoutattributesforelementsinrect = [super layoutattributesforelementsinrect:rect];
  
  for (uicollectionviewlayoutattributes *layoutattributes in layoutattributesforelementsinrect) {
    switch (layoutattributes.representedelementcategory) {
      case uicollectionelementcategorycell: {
        [self applylayoutattributes:layoutattributes];
      } break;
      default: {
        // do nothing...
      } break;
    }
  }
  
  return layoutattributesforelementsinrect;
}
 
- (uicollectionviewlayoutattributes *)layoutattributesforitematindexpath:(nsindexpath *)indexpath {
  uicollectionviewlayoutattributes *layoutattributes = [super layoutattributesforitematindexpath:indexpath];
  
  switch (layoutattributes.representedelementcategory) {
    case uicollectionelementcategorycell: {
      [self applylayoutattributes:layoutattributes];
    } break;
    default: {
      // do nothing...
    } break;
  }
  
  return layoutattributes;
}
 
#pragma mark - uigesturerecognizerdelegate methods
 
- (bool)gesturerecognizershouldbegin:(uigesturerecognizer *)gesturerecognizer {
  if ([self.pangesturerecognizer isequal:gesturerecognizer]) {
    return (self.selecteditemindexpath != nil);
  }
  return yes;
}
 
- (bool)gesturerecognizer:(uigesturerecognizer *)gesturerecognizer shouldrecognizesimultaneouslywithgesturerecognizer:(uigesturerecognizer *)othergesturerecognizer {
  if ([self.longpressgesturerecognizer isequal:gesturerecognizer]) {
    return [self.pangesturerecognizer isequal:othergesturerecognizer];
  }
  
  if ([self.pangesturerecognizer isequal:gesturerecognizer]) {
    return [self.longpressgesturerecognizer isequal:othergesturerecognizer];
  }
  
  return no;
}
 
#pragma mark - key-value observing methods
 
- (void)observevalueforkeypath:(nsstring *)keypath ofobject:(id)object change:(nsdictionary *)change context:(void *)context {
  if ([keypath isequaltostring:klxcollectionviewkeypath]) {
    if (self.collectionview != nil) {
      [self setupcollectionview];
    } else {
      [self invalidatesscrolltimer];
    }
  }
}
 
#pragma mark - notifications
 
- (void)handleapplicationwillresignactive:(nsnotification *)notification {
  self.pangesturerecognizer.enabled = no;
  self.pangesturerecognizer.enabled = yes;
}
 
#pragma mark - depreciated methods
 
#pragma mark starting from 0.1.0
- (void)setupgesturerecognizersoncollectionview {
  // do nothing...
}
 
@end

效果图:

 iOS模仿电子书首页实现书架布局样式

三、实现自己的layout

首先继承lxreorderablecollectionviewflowlayout,让该类具有重新排序功能。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//
// fwbookshelfcollectionviewlayout.h
// fwpersonalapp
//
// created by hzkmn on 16/2/18.
// copyright © 2016年 forrstwoo. all rights reserved.
//
 
#import "lxreorderablecollectionviewflowlayout.h"
 
extern nsstring * const fwbookshelfcollectionviewlayoutdecorationviewkind;
 
@interface fwbookshelfcollectionviewlayout : 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
//
// created by hzkmn on 16/2/18.
// copyright © 2016年 forrstwoo. all rights reserved.
//
 
#import "fwbookshelfcollectionviewlayout.h"
 
#import "fwbookshelfdecarationview.h"
 
nsstring * const fwbookshelfcollectionviewlayoutdecorationviewkind = @"fwbookshelfcollectionviewlayoutdecorationviewkind";
 
@interface fwbookshelfcollectionviewlayout ()
 
@property (nonatomic, strong) nsdictionary *bookshelfrectanges;
@property nsinteger countofrow;
 
@end
 
@implementation fwbookshelfcollectionviewlayout
 
- (void)preparelayout
{
  [super preparelayout];
  
  [self registerclass:[fwbookshelfdecarationview class] fordecorationviewofkind:fwbookshelfcollectionviewlayoutdecorationviewkind];
  
  nsmutabledictionary *dictionary = [nsmutabledictionary dictionary];
  
  nsinteger itemcount = [self.collectionview numberofitemsinsection:0];
  self.countofrow = ceilf(itemcount / 3.0);
  for (int row = 0; row < self.countofrow; row++)
  {
    dictionary[[nsindexpath indexpathforitem:row insection:0]] = [nsvalue valuewithcgrect:cgrectmake(0, kdecorationviewheight * row, screensize.width, kdecorationviewheight)];
  }
  
  self.bookshelfrectanges = [nsdictionary dictionarywithdictionary:dictionary];
}
 
#pragma mark runtime layout calculations
- (nsarray *)layoutattributesforelementsinrect:(cgrect)rect
{
  // call super so flow layout can return default attributes for all cells, headers, and footers
  // note: flow layout has already taken care of the cell view layout attributes! :)
  nsarray *array = [super layoutattributesforelementsinrect:rect];
  
  // create a mutable copy so we can add layout attributes for any shelfs that
  // have frames that intersect the rect the collectionview is interested in
  nsmutablearray *newarray = [array mutablecopy];
  //  nslog(@"in rect:%@",nsstringfromcgrect(rect));
  // add any decoration views (shelves) who's rect intersects with the
  // cgrect passed to the layout by the collectionview
  [self.bookshelfrectanges enumeratekeysandobjectsusingblock:^(id key, id shelfrect, bool *stop) {
    //    nslog(@"[shelfrect cgrectvalue]:%@",nsstringfromcgrect([shelfrect cgrectvalue]));
    
    if (cgrectintersectsrect([shelfrect cgrectvalue], rect))
    {
      uicollectionviewlayoutattributes *shelfattributes =
      [self layoutattributesfordecorationviewofkind:fwbookshelfcollectionviewlayoutdecorationviewkind
                       atindexpath:key];
      [newarray addobject:shelfattributes];
    }
  }];
  
  for (int i = 0; i < [self.collectionview numberofitemsinsection:0]; i++)
  {
    nsindexpath *indexpath = [nsindexpath indexpathforitem:i insection:0];
    
    [newarray addobject:[self layoutattributesforitematindexpath:indexpath]];
  }
  
  return [newarray copy];
}
 
- (uicollectionviewlayoutattributes *)layoutattributesforitematindexpath:(nsindexpath *)indexpath
{
  //  nslog(@"%@", nsstringfromcgsize([self screensize]));375 667
  uicollectionviewlayoutattributes *attris = [uicollectionviewlayoutattributes layoutattributesforcellwithindexpath:indexpath];
  
  nsinteger currentrow = indexpath.item / 3;
  cgrect frame = cgrectmake(20 + (indexpath.item % 3) * (kcellwidth + 17.5), 35+ currentrow * (kcellheight + 65), kcellwidth, kcellheight);
  attris.frame = frame;
  attris.zindex = 1;
  
  return attris;
}
 
- (uicollectionviewlayoutattributes *)layoutattributesfordecorationviewofkind:(nsstring *)decorationviewkind atindexpath:(nsindexpath *)indexpath
{
  
  id shelfrect = self.bookshelfrectanges[indexpath];
  
  // this should never happen, but just in case...
  if (!shelfrect)
    return nil;
  
  uicollectionviewlayoutattributes *attributes =
  [uicollectionviewlayoutattributes layoutattributesfordecorationviewofkind:decorationviewkind
                                withindexpath:indexpath];
  attributes.frame = [shelfrect cgrectvalue];
  //  nslog(@"uicollectionviewlayoutattributes :.%@", nsstringfromcgrect([shelfrect cgrectvalue]));
  
  attributes.zindex = -1; // shelves go behind other views
  
  return attributes;
}
 
- (cgsize)collectionviewcontentsize
{
  cgsize contentsize = cgsizemake(self.collectionview.bounds.size.width, self.countofrow * kdecorationviewheight + 20);
  
  return contentsize;
}
 
@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
//
// created by hzkmn on 16/2/17.
// copyright © 2016年 forrstwoo. all rights reserved.
//
 
 
 
#import "fwancientpoetrycollectionviewcontroller.h"
 
#import "fwbookshelfdecarationview.h"
#import "fwbookshelfcollectionviewlayout.h"
#import "fwbookcategoryviewcontroller.h"
 
@interface fwancientpoetrycollectionviewcontroller () <lxreorderablecollectionviewdatasource, lxreorderablecollectionviewdelegateflowlayout>
 
@property (nonatomic, strong) nsmutablearray *books;
 
@end
 
@implementation fwancientpoetrycollectionviewcontroller
 
static nsstring * const cellreuseidentifier = @"cell";
- (void)viewdidload {
  [super viewdidload];
  self.title = @"古籍";
  self.collectionview.backgroundcolor = [uicolor colorwithpatternimage:[uiimage imagenamed:@"bookshelfbackground.png"]];
  [self.collectionview registerclass:[uicollectionviewcell class] forcellwithreuseidentifier:cellreuseidentifier];
  self.books = [[nsmutablearray alloc] initwitharray:[self booknameofallbooks]];
}
 
- (nsarray *)booknameofallbooks
{
 return [[fwdatamanager getdataforpoetry] allkeys];
}
 
#pragma mark <uicollectionviewdatasource>
 
- (nsinteger)numberofsectionsincollectionview:(uicollectionview *)collectionview
{
  return 1;
}
 
- (nsinteger)collectionview:(uicollectionview *)collectionview numberofitemsinsection:(nsinteger)section
{
  return [self.books count];
}
 
- (uicollectionviewcell *)collectionview:(uicollectionview *)collectionview cellforitematindexpath:(nsindexpath *)indexpath
{
  uicollectionviewcell *cell = [collectionview dequeuereusablecellwithreuseidentifier:cellreuseidentifier forindexpath:indexpath];
  uiimage *image = [uiimage imagenamed:self.books[indexpath.item]];
  cell.backgroundcolor = [uicolor colorwithpatternimage:image];
 
  return cell;
}
 
- (void)collectionview:(uicollectionview *)collectionview itematindexpath:(nsindexpath *)fromindexpath willmovetoindexpath:(nsindexpath *)toindexpath
{
  nsstring *thebookname = self.books[fromindexpath.item];
  [self.books removeobjectatindex:fromindexpath.item];
  [self.books insertobject:thebookname atindex:toindexpath.item];
}
 
#pragma mark - uicollectionviewdelegateflowlayout
 
- (cgsize)collectionview:(uicollectionview *)collectionview layout:(uicollectionviewlayout *)collectionviewlayout sizeforitematindexpath:(nsindexpath *)indexpath
{
  return cgsizemake(kcellwidth, kcellheight);
}
 
- (void)collectionview:(uicollectionview *)collectionview didselectitematindexpath:(nsindexpath *)indexpath
{
  fwbookcategoryviewcontroller *vc = [[fwbookcategoryviewcontroller alloc] initwithurlstring:[[fwdatamanager getdataforpoetry] objectforkey:self.books[indexpath.item]]];
  [self.navigationcontroller pushviewcontroller:vc animated:yes];
}
 
- (void)didreceivememorywarning {
  [super didreceivememorywarning];
 
  [self.books removeallobjects];
  self.books = nil;
}
 
@end

以上就是本文的全部内容,ios模仿实现书架效果,类似于手机上的掌上阅读软件的首页,希望本文对大家的学习有所帮助。

延伸 · 阅读

精彩推荐
  • IOSiOS逆向教程之logify跟踪方法的调用

    iOS逆向教程之logify跟踪方法的调用

    这篇文章主要给大家介绍了关于iOS逆向教程之logify跟踪方法调用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学...

    Mr.Guo11472021-04-28
  • IOS谈一谈iOS单例模式

    谈一谈iOS单例模式

    这篇文章主要和大家谈一谈iOS中的单例模式,单例模式是一种常用的软件设计模式,想要深入了解iOS单例模式的朋友可以参考一下...

    彭盛凇11872021-01-19
  • IOSiOS中时间与时间戳的相互转化实例代码

    iOS中时间与时间戳的相互转化实例代码

    这篇文章主要介绍了iOS中时间与时间戳的相互转化实例代码,非常具有实用价值,需要的朋友可以参考下。...

    张无忌!4812021-03-09
  • IOSIOS网络请求之AFNetWorking 3.x 使用详情

    IOS网络请求之AFNetWorking 3.x 使用详情

    本篇文章主要介绍了IOS网络请求之AFNetWorking 3.x 使用详情,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    总李写代码6892021-03-04
  • IOSiOS10 Xcode8适配7个常见问题汇总

    iOS10 Xcode8适配7个常见问题汇总

    这篇文章主要为大家详细汇总了iOS10 Xcode8适配7个常见问题,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    索马里猫10332021-02-01
  • IOSiOS APP实现微信H5支付示例总结

    iOS APP实现微信H5支付示例总结

    这篇文章主要介绍了iOS APP实现微信H5支付示例总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下...

    一张小A11332021-06-01
  • IOSxcode8提交ipa失败无法构建版本问题的解决方案

    xcode8提交ipa失败无法构建版本问题的解决方案

    xcode升级到xcode8后发现构建不了新的版本。怎么解决呢?下面小编给大家带来了xcode8提交ipa失败无法构建版本问题的解决方案,非常不错,一起看看吧...

    Cinna丶7542021-02-03
  • IOSiOS常见的几个修饰词深入讲解

    iOS常见的几个修饰词深入讲解

    这篇文章主要给大家介绍了关于iOS常见的几个修饰词的相关资料,iOS修饰词包括assign、weak、strong、retain、copy、nonatomic、atomic、readonly、readwrite,文中通过示...

    郡王丶千夜7422021-05-10