iOS实战:动画实战-自定义下拉刷新控件

前言

本文是上一篇文章上手CAShapeLayer,动画其实并不难 的实战,用到的知识有CAShapeLayer、UIBezierPath和CABasicAnimation。如果对这些类不大了解,可先去基础篇看看。

正文

这次要做的是一个简单的下拉刷新控件,主要还是练习刚上手的动画。

一、效果预览

效果预览.gif

二、动画分析

随着下拉tableView,蓝色的图层的填充比会越来越大,直到充满,开始刷新。蓝色的圆弧开始旋转。

三、开始代码

1.新建自定义刷新控件

首先新建自定义刷新控件,继承自UIView。然后给这个类添加属性和方法。这里思考传递事件的方法(也就是当下拉到一定程度告诉控制器该刷新了)。我这里选用的是
- (id)performSelector:(SEL)aSelector;方法来传递事件的。当然也可以用block或者delegate。所以:

@interface YQRefreshHeadView : UIView
@property (nonatomic, weak) id target;
@property (nonatomic, assign) SEL action;
@property (nonatomic, weak) UIScrollView *scrollView;
- (void)startAnimation;
- (void)endAnimation;
@end

2.新建UIScrollView的拓展类

为了能够更加方便,我新建了UIScrollView的拓展类。拓展类代码如下:
.h:

@interface UIScrollView (YQRefreshHeadView)
- (YQRefreshHeadView *)attachRefreshHeadViewWithTarget:(id)target action:(SEL)action;
@end

.m:

- (YQRefreshHeadView *)attachRefreshHeadViewWithTarget:(id)target action:(SEL)action
{
    YQRefreshHeadView *headView = [[YQRefreshHeadView alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 50)/2, -50, 50, 50)];
    headView.target = target;
    headView.action = action;
    headView.scrollView = self;
    [self addSubview:headView];
    return headView;
}

这样在使用刷新控件的时候,直接这样:

self.rhv = [tableView attachRefreshHeadViewWithTarget:self action:@selector(reloadData)];

这样就绑定上去了,当然需要一个返回值,毕竟刷新完成后要让它停止转动的,就像这样:[self.rhv endAnimation];

3.设置好控件里的layer

重写- (instancetype)initWithFrame:(CGRect)frame方法,并在其中设置layer。

- (CAShapeLayer *)bottomLayer
{
    if (_bottomLayer == nil) {
        _bottomLayer = [CAShapeLayer layer];
        _bottomLayer.fillColor = [UIColor clearColor].CGColor;
        _bottomLayer.strokeColor = [UIColor lightGrayColor].CGColor;
        _bottomLayer.lineCap = kCALineCapRound;
        _bottomLayer.lineJoin = kCALineJoinRound;
        _bottomLayer.lineWidth = 2;
        _bottomLayer.frame = CGRectMake(self.bounds.size.height*0.2, self.bounds.size.height*0.2, self.bounds.size.height*0.6, self.bounds.size.height*0.6);
        _bottomLayer.path = [UIBezierPath bezierPathWithOvalInRect:_bottomLayer.bounds].CGPath;
    }
    return _bottomLayer;
}

- (CAShapeLayer *)topLayer
{
    if (!_topLayer) {
        _topLayer = [CAShapeLayer layer];
        _topLayer.fillColor = [UIColor clearColor].CGColor;
        _topLayer.strokeColor = [UIColor colorWithRed:0.0431 green:0.7569 blue:0.9412 alpha:1.0].CGColor;
        _topLayer.lineCap = kCALineCapRound;
        _topLayer.lineJoin = kCALineJoinRound;
        _topLayer.lineWidth = 2;
        _topLayer.frame = self.bottomLayer.frame;
        _topLayer.path = [UIBezierPath bezierPathWithOvalInRect:_topLayer.bounds].CGPath;
        [_topLayer setValue:@(-M_PI_2) forKeyPath:@"transform.rotation.z"];
        _topLayer.strokeEnd = 0;
    }
    return _topLayer;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        [self initViews];
    }
    return self;
}

- (void)initViews
{
    [self.layer addSublayer:self.bottomLayer];
    [self.layer addSublayer:self.topLayer];
}
注意!!!

这里有一个要注意的。+ (instancetype)bezierPathWithOvalInRect:(CGRect)rect;该方法开始绘制的点是该圆最右边的那个点。所以如果只是单纯地用这个方法绘制圆的话,在下拉的时候会出现如下问题:

不旋转会出现的问题.gif

所以需要旋转topLayer。

[_topLayer setValue:@(-M_PI_2) forKeyPath:@"transform.rotation.z"];

这样看上去,这个圆的开始绘制点就在最顶端那点了。

4.设置监听并写监听方法

在刚开始写时,我遇到了问题。原本我打算在- (instancetype)initWithFrame:(CGRect)frame方法里添加监听的。就像这样:

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        [self initViews];
        [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionInitial context:nil];
    }
    return self;
}

- (void)initViews
{
    [self.layer addSublayer:self.bottomLayer];
    [self.layer addSublayer:self.topLayer];
}

但是没有效果。原因是设置监听时self.scrollView还是空的。原因还得看UIScrollView拓展类:

- (YQRefreshHeadView *)attachRefreshHeadViewWithTarget:(id)target action:(SEL)action
{
    YQRefreshHeadView *headView = [[YQRefreshHeadView alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 50)/2, -50, 50, 50)];
    headView.target = target;
    headView.action = action;
    headView.scrollView = self;
    [self addSubview:headView];
    return headView;
}

在执行initWithFrame的时候,scrollView还没有设置上去。
我的解决方法是,加一个- (void)addObserver;公共方法,在初始化控件并设置完属性后,手动添加监听。
该方法实现:

- (void)addObserver
{
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionInitial context:nil];
}

这时的scrollView已经设置上去了。下面是监听对应的方法:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    UIScrollView *scrollView = object;
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > -30) {
        return;
    }
    // 向下拖拽时计算圆弧的结束值
    CGFloat dragProgress = MIN(fabs(offsetY+30)/50, 1);
    NSLog(@"%f", dragProgress);
    CGFloat strokeEnd = dragProgress;
    self.topLayer.strokeEnd = strokeEnd;
    
    // 满足刷新条件
    if (!scrollView.isDragging && fabs(offsetY+30)/50>1) {
        [scrollView setContentOffset:CGPointMake(0, -80) animated:NO];
        [self startAnimation];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self.target performSelector:self.action];
#pragma clang diagnostic pop
    }
}

解释:下拉一定像素后,设置topLayerstrokeEnd属性,这样就会有上面的效果啦。同时拉到一定程度后,开始旋转的动画并告诉控制器该刷新了。

5.写开始动画和结束动画方法

- (void)startAnimation
{
    self.topLayer.strokeEnd = 0.2;
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = @(M_PI * 2 *0.72);
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    rotationAnimation.duration = 2;
    rotationAnimation.repeatCount = HUGE;
    rotationAnimation.fillMode = kCAFillModeForwards;
    rotationAnimation.removedOnCompletion = NO;
    [self.topLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

这里用的是CABasicAnimation,动画的KeyPathtransform.rotation.z
结束动画方法:

- (void)endAnimation
{
    [self.topLayer removeAllAnimations];
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

这样,最简单的刷新控件就完成了啦。看看如何调用:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - self.navigationController.navigationBar.bounds.size.height - 20) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    self.rhv = [tableView attachRefreshHeadViewWithTarget:self action:@selector(reloadData)];
}

#pragma mark - 内部方法
- (void)reloadData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.rhv endAnimation];
    });
}

最后

本文的github地址:https://github.com/JabberYQ/YQRefreshHeadViewDemo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容