• Stars
    star
    307
  • Rank 136,109 (Top 3 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created almost 6 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

QiCardView,一款由QiShare所开源的自定义卡片式控件。

前言:因项目中需求,需要做一个卡片式控件。故QiCardView诞生了。

首先,先来看一下QiCardView的效果图:

从命名来看,QiCardView,顾名思义,是一个可定制的卡片式UI控件。 从设计来看,QiCardView仿照UITableView的设计,支持cell复用,节省了资源。

话不多说,先来看下整体架构~

一、QiCardView整体架构设计

架构层面仿照了UITableView的设计,采用了cell复用策略。 在此基础上,融入了一些手势操作,更加富有交互性。

上架构图:

两个主类分别为QiCardViewQiCardViewCell。(仿照UITableView+UITableViewCell的设计)

  • QiCardView 下有两个代理:QiCardViewDataSourceQiCardViewDelegate。(与UITableView的代理方法类似)
  • QiCardViewCell 下有一个代理:QiCardViewCellDelegate。(这个代理可以不关心,主要目的是辅助QiCardView里的一些处理逻辑)

二、如何自定义使用QiCardView?

Cell自定义很简单,只要新建一个类(例如:QiCardViewItemCell)继承自QiCardViewCell即可。

在Controller中,基本使用上几乎与UITableView类似。

  • 初始化CardView方法:

在上Demo之前,先介绍几个可以自定义的配置属性:

属性 类型 介绍
visibleCount NSInteger 卡片Cell可见数量(默认3)。因为有复用策略,所以即实际创建的Cell数量。
lineSpacing CGFloat 行间距(默认10.0,可自行计算scale比例来做间距)
interitemSpacing CGFloat 列间距(默认10.0,可自行计算scale比例来做间距)
maxAngle CGFloat 侧滑最大角度(默认15°)。值约小越容易划出,越大约不好划出。
maxRemoveDistance CGFloat 最大移除距离(默认屏幕的1/4),滑动距离不够时归位。
isAlpha CGFloat cell是否需要渐变透明度。(默认YES)
- (void)initViews {
    
    _cardView = [[QiCardView alloc] initWithFrame:CGRectMake(25.0, 150.0, self.view.frame.size.width - 50.0, 420.0)];
    _cardView.backgroundColor = [UIColor lightGrayColor];//!< 为了指出carddView的区域,指明背景色
    _cardView.dataSource = self;
    _cardView.delegate = self;
    _cardView.visibleCount = 4;
    _cardView.lineSpacing = 15.0;
    _cardView.interitemSpacing = 10.0;
    _cardView.maxAngle = 10.0;
    _cardView.isAlpha = YES;
    _cardView.maxRemoveDistance = 100.0;
    _cardView.layer.cornerRadius = 10.0;
    [_cardView registerClass:[QiCardItemCell class] forCellReuseIdentifier:qiCardCellId];
    [self.view addSubview:_cardView];
}
  • 数据源:QiCardViewDataSource: 首先controller要遵守协议:<QiCardViewDataSource>
#pragma mark - QiCardViewDataSource

- (QiCardItemCell *)cardView:(QiCardView *)cardView cellForRowAtIndex:(NSInteger)index {
    
    QiCardItemCell *cell = [cardView dequeueReusableCellWithIdentifier:qiCardCellId];
    cell.cellData = _cellItems[index];
    //...

    return cell;
}

- (NSInteger)numberOfCountInCardView:(UITableView *)cardView {
    return _cellItems.count;
}
  • 代理:QiCardViewDelegate: 还是首先controller需要遵守协议:<QiCardViewDelegate>
#pragma mark - QiCardViewDelegate

- (void)cardView:(QiCardView *)cardView didRemoveLastCell:(QiCardViewCell *)cell forRowAtIndex:(NSInteger)index {
    [cardView reloadDataAnimated:YES];
}

- (void)cardView:(QiCardView *)cardView didRemoveCell:(QiCardViewCell *)cell forRowAtIndex:(NSInteger)index {
    NSLog(@"didRemoveCell forRowAtIndex = %ld", index);
}

- (void)cardView:(QiCardView *)cardView didDisplayCell:(QiCardViewCell *)cell forRowAtIndex:(NSInteger)index {
    
    NSLog(@"didDisplayCell forRowAtIndex = %ld", index);
}

- (void)cardView:(QiCardView *)cardView didMoveCell:(QiCardViewCell *)cell forMovePoint:(CGPoint)point {
    NSLog(@"move point = %@", NSStringFromCGPoint(point));
}

三、QiCardView的技术点

3.1 QiCardViewCell复用策略实现

  1. 注册Cell: 两种方式:registerNibregisterClass。 很简单。
/** 注册cell方法一:Nib */
- (void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier {
    self.nib = nib;
    self.identifier = identifier;
}

/** 注册cell方法二:Class */
- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier {
    self.cellClass = cellClass;
    self.identifier = identifier;
}
  1. 获取缓存Cell策略: 先看缓存池中是否有相同ID(identifier)的Cell,有的话,直接返回Cell。 若缓存池中没有,那么就new一个新的Cell啦~
/** 获取缓存cell */
- (__kindof QiCardViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier {
    for (QiCardViewCell *cell in self.reusableCells) {
        if ([cell.reuseIdentifier isEqualToString:identifier]) {
            [self.reusableCells removeObject:cell];
            
            return cell;
        }
    }
    if (self.nib) {
        QiCardViewCell *cell = [[self.nib instantiateWithOwner:nil options:nil] lastObject];
        cell.reuseIdentifier = identifier;
        
        return cell;
    } else if (self.cellClass) { // 注册class
        QiCardViewCell *cell = [[self.cellClass alloc] initWithReuseIdentifier:identifier];
        cell.reuseIdentifier = identifier;
        
        return cell;
    }
    return nil;
}
  1. 当cell走DidRemoveFromSuperView方法时,把cell加入缓存池。
- (void)cardViewCellDidRemoveFromSuperView:(QiCardViewCell *)cell {

    //...    

    [self.reusableCells addObject:cell];

    //...
}

3.2 cell重叠透明度渐变的实现

  1. 首先声明了一个静态变量:moveCount来记录翻卡次数。(以便将cell的index与卡片的index逻辑关联)
static int moveCount = 0;//!< 记录翻页次数
  1. 逻辑:每个CardCell 在 “remove from super view” 的时候 moveCount+1。
#pragma mark - QiCardViewCellDelagate

- (void)cardViewCellDidRemoveFromSuperView:(QiCardViewCell *)cell {
    
    moveCount++;
    
    //....
}
  1. 逻辑:在reload方法中,需要将moveCount置0。(很好理解,reload时,moveCount需要重新开始计算)
- (void)reloadDataAnimated:(BOOL)animated {
    
    moveCount = 0;//!< 渐变需要
    
   //...
}
  1. 关键逻辑:在每次更新布局时,设置每个Cell的渐变值(即alpha
/** 更新布局(动画) */
- (void)updateLayoutVisibleCellsWithAnimated:(BOOL)animated {
    
    //...

    if (_isAlpha) {
        BOOL isTopCell = (i == _currentIndex - moveCount);
        if (isTopCell) {//!< 如果是最上面的Cell就透明度为1
            cell.alpha = 1.0;
         } else {
            cell.alpha = (i + 1.9) * 1.0/self.visibleCells.count;
        }
    }

    //...

}

3.3 手势操作实现

这部分主要是手势+动画。 细节比较多,小而杂。 详细逻辑,请见源码

#define Qi_SNAPSHOTVIEW_TAG 999
#define Qi_DEGREES_TO_RADIANS(angle) (angle / 180.0 * M_PI)

- (void)panGestureRecognizer:(UIPanGestureRecognizer*)pan {
    
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
            self.currentPoint = CGPointZero;
            break;
        case UIGestureRecognizerStateChanged: {
            CGPoint movePoint = [pan translationInView:pan.view];
            self.currentPoint = CGPointMake(self.currentPoint.x + movePoint.x , self.currentPoint.y + movePoint.y);
            
            CGFloat moveScale = self.currentPoint.x / self.maxRemoveDistance;
            if (ABS(moveScale) > 1.0) {
                moveScale = (moveScale > 0) ? 1.0 : -1.0;
            }
            CGFloat angle = Qi_DEGREES_TO_RADIANS(self.maxAngle) * moveScale;
            CGAffineTransform transRotation = CGAffineTransformMakeRotation(angle);
            self.transform = CGAffineTransformTranslate(transRotation, self.currentPoint.x, self.currentPoint.y);
            
            if (self.cell_delegate && [self.cell_delegate respondsToSelector:@selector(cardViewCellDidMoveFromSuperView:forMovePoint:)]) {
                [self.cell_delegate cardViewCellDidMoveFromSuperView:self forMovePoint:self.currentPoint];
            }
            [pan setTranslation:CGPointZero inView:pan.view];
        }
            break;
        case UIGestureRecognizerStateEnded:
            [self didPanStateEnded];
            break;
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateFailed:
            [self restoreCellLocation];
            break;
        default:
            break;
    }
}

// 手势结束操作(不考虑上下位移)
- (void)didPanStateEnded {
    // 右滑移除
    if (self.currentPoint.x > self.maxRemoveDistance) {
        __block UIView *snapshotView = [self snapshotViewAfterScreenUpdates:NO];
        snapshotView.transform = self.transform;
        [self.superview.superview addSubview:snapshotView];
        [self didCellRemoveFromSuperview];
        
        CGFloat endCenterX = [UIScreen mainScreen].bounds.size.width/2 + self.frame.size.width * 1.5;
        [UIView animateWithDuration:Qi_DefaultDuration animations:^{
            CGPoint center = self.center;
            center.x = endCenterX;
            snapshotView.center = center;
        } completion:^(BOOL finished) {
            [snapshotView removeFromSuperview];
        }];
    }
    // 左滑移除
    else if (self.currentPoint.x < -self.maxRemoveDistance) {
        __block UIView *snapshotView = [self snapshotViewAfterScreenUpdates:NO];
        snapshotView.transform = self.transform;
        [self.superview.superview addSubview:snapshotView];
        [self didCellRemoveFromSuperview];
        
        CGFloat endCenterX = -([UIScreen mainScreen].bounds.size.width/2 + self.frame.size.width);
        [UIView animateWithDuration:Qi_DefaultDuration animations:^{
            CGPoint center = self.center;
            center.x = endCenterX;
            snapshotView.center = center;
        } completion:^(BOOL finished) {
            [snapshotView removeFromSuperview];
        }];
    }
    // 滑动距离不够归位
    else {
        [self restoreCellLocation];
    }
}

// 还原卡片位置
- (void)restoreCellLocation {
    
    [UIView animateWithDuration:Qi_SpringDuration delay:0
         usingSpringWithDamping:Qi_SpringWithDamping
          initialSpringVelocity:Qi_SpringVelocity
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         self.transform = CGAffineTransformIdentity;
                     } completion:nil];
}

// 卡片移除处理
- (void)didCellRemoveFromSuperview {
    
    self.transform = CGAffineTransformIdentity;
    [self removeFromSuperview];
    if ([self.cell_delegate respondsToSelector:@selector(cardViewCellDidRemoveFromSuperView:)]) {
        [self.cell_delegate cardViewCellDidRemoveFromSuperView:self];
    }
}

- (void)removeFromSuperviewSwipe:(QiCardCellSwipeDirection)direction {
    
    switch (direction) {
        case QiCardCellSwipeDirectionLeft: {
            [self removeFromSuperviewLeft];
        }
            break;
        case QiCardCellSwipeDirectionRight: {
            [self removeFromSuperviewRight];
        }
            break;
        default:
            break;
    }
}

// 向左边移除动画
- (void)removeFromSuperviewLeft {
    __block UIView *snapshotView = [self snapshotViewAfterScreenUpdates:NO];
    [self.superview.superview addSubview:snapshotView];
    [self didCellRemoveFromSuperview];
    
    CGAffineTransform transRotation = CGAffineTransformMakeRotation(-Qi_DEGREES_TO_RADIANS(self.maxAngle));
    CGAffineTransform transform = CGAffineTransformTranslate(transRotation, 0, self.frame.size.height/4.0);
    CGFloat endCenterX = -([UIScreen mainScreen].bounds.size.width/2 + self.frame.size.width);
    [UIView animateWithDuration:Qi_DefaultDuration animations:^{
        CGPoint center = self.center;
        center.x = endCenterX;
        snapshotView.center = center;
        snapshotView.transform = transform;
    } completion:^(BOOL finished) {
        [snapshotView removeFromSuperview];
    }];
}

// 向右边移除动画
- (void)removeFromSuperviewRight {
    __block UIView *snapshotView = [self snapshotViewAfterScreenUpdates:NO];
    snapshotView.frame = self.frame;
    [self.superview.superview addSubview:snapshotView];
    [self didCellRemoveFromSuperview];
    
    CGAffineTransform transRotation = CGAffineTransformMakeRotation(Qi_DEGREES_TO_RADIANS(self.maxAngle));
    CGAffineTransform transform = CGAffineTransformTranslate(transRotation, 0, self.frame.size.height/4.0);
    CGFloat endCenterX = [UIScreen mainScreen].bounds.size.width/2 + self.frame.size.width * 1.5;
    [UIView animateWithDuration:Qi_DefaultDuration animations:^{
        CGPoint center = self.center;
        center.x = endCenterX;
        snapshotView.center = center;
        snapshotView.transform = transform;
    } completion:^(BOOL finished) {
        [snapshotView removeFromSuperview];
    }];
}

四、未来可能优化的点

  • 设计层面:如果将手势操作融入QiCardView中,将QiCardViewCell变成纯粹的Cell,会不会更好。(思考中)
  • 应用层面:目前只支持一个ID的Cell重用,未来渴望拓展成多个ID的Cell都可重用。(PS:因为只存了一个ID,后续考虑存数组,以及对应的Cell缓存池数组。以此猜测UITableView的内部实现。)

QiShare博客原文链接:https://juejin.im/post/5c613dae518825625f3a2af8

More Repositories

1

Qi_ObjcMsgHook

QiLagMonitor is an iOS performance detection tool, which can monitor method time and method call stack through hook objc_msgsend.
Objective-C
122
star
2

QiAppRunInBackground

Objective-C
37
star
3

QiStackFrameLogger

A lightweight thread method call stack printing tool.
Objective-C
31
star
4

QiWebSocket

A websocket demo(Client & Server). The client is written in swift and the server is written in Golang.
Swift
13
star
5

QiLayoutDemo

iOS 几种常用的布局方法
Objective-C
9
star
6

QiSignInWithApple

Sign In With Apple Demo
Objective-C
9
star
7

QiLogTool

日志小工具
Objective-C
9
star
8

QiRestoration

Objective-C
8
star
9

QiPagesContainer

滑动选择控件,QiPagesContainer
Objective-C
8
star
10

QiSafeType

取数据的时候,进行取值安全性处理,防止一些崩溃。
Objective-C
6
star
11

QiShareButtonDemo

Objective-C
5
star
12

QiMultiThread

iOS中的多线程
Objective-C
5
star
13

QiNetwork

Objective-C
4
star
14

QiRecursiveDemo

对递归尾递归做简单介绍
Objective-C
4
star
15

QiFlutterPage

用Flutter写一个简单页面
Dart
4
star
16

QiSwiftUIAnimation

用SwiftUI 给视图添加常用动画及转场动画
Swift
4
star
17

QiSensorsDemo

iOS 常用传感器
Objective-C
4
star
18

QiChartsDemo

QiShare可视化组件
Swift
4
star
19

QiDarkMode

适配iOS13DarkMode
Objective-C
4
star
20

QiCodeStandard

Objective-C
3
star
21

Qi_MAMapDemo

高德地图SDK应用实践
Swift
3
star
22

QiCodeSnippets

QiShare自定义的常用代码块
Objective-C
3
star
23

QiTimer

Objective-C
3
star
24

QiDrawRect

关于UIView的DrawRect...
Objective-C
3
star
25

QiPasswordAutoFill

PasswordAutoFillDemo
Objective-C
3
star
26

QiStrongVsCopy

Objective-C
3
star
27

QiAlgorithms

图解算法Demo存储
Python
2
star
28

QiTransform

QiTransform
Swift
2
star
29

QiBar

QiBar
Objective-C
2
star
30

QiRunLoopDemo1

Objective-C
2
star
31

QiSerialCABasicAnimation

CABasicAnimation之实现串行效果
Objective-C
2
star
32

QiTestFramework

无需import目标framework,就可使用其中方法
Objective-C
2
star
33

QiButton

UIButton 常用功能代码
Objective-C
2
star
34

QiToast

A lightweight iOS toast written by swift.
Swift
2
star
35

QiButton_UIControlEvents

UIButton之UIControlEvents
Objective-C
2
star
36

QiKeychain

钥匙串(keychain)的基本使用
Objective-C
2
star
37

QiButton_ChangeEffectiveClickArea

改变UIButton的有效点击区域
Objective-C
2
star
38

QiFrontEndStarPlan

前端星计划部分课程学习
HTML
2
star
39

QiFirstTasteOfAnimation

CABasicAnimation使用简单介绍
Objective-C
2
star
40

QiLocalization

介绍iOS本地化相关内容
Objective-C
1
star
41

QiDesignatedInitializer

iOS 指定初始化方法
Objective-C
1
star
42

yueji

Dart
1
star
43

QiAuthorizationManager

iOS 系统权限管理 (iOS 10+)
Objective-C
1
star
44

QiBitcode

了解iOS Bitcode
1
star
45

QiButton_UIButtonType

UIButton之UIButtonType介绍
Objective-C
1
star
46

QiLagMonitor

1
star
47

QiOrientation

QiOrientation
Objective-C
1
star
48

QiDebugDemo

Xcode常用调试方法(静态分析、断点、控制台)
Objective-C
1
star
49

QiModularization

iOS 组件化方案验证
Objective-C
1
star
50

QiKVO-KVC

iOS中的KVO和KVC
Objective-C
1
star
51

QiShare.github.io

QiShare‘s Blog
HTML
1
star
52

QiKeyFrameAnimation

KeyFrameAnimation使用简单介绍
Objective-C
1
star
53

QiShareBlogTalk

官网的评论功能
1
star
54

QiPublicPods

QiPublicPods 公有库的介绍及使用
Ruby
1
star
55

QiRecursion

Objective-C
1
star
56

QiNSCopyingDemo

QiNSCopyingDemo
1
star