iOS 自定义下拉刷新控件 —— 解决图片拉伸与数据刷新冲突

前言

iOS 的下拉刷新用的最广泛的应该是 MJRefresh. 但是有时候不能满足我们的特殊需求. 如下拉时候, 设置的图片放大, 那么用该控件刷新就会有些问题. 今天作者 就简单封装一个 刷新控件, 仅为各位提供个思路.

效果.gif

一. 控件

RefreshView.h文件

#import <UIKit/UIKit.h>

typedef NS_ENUM(NSInteger, RefreshViewStyle) {
    RefreshViewStyleNormal,  // 普通状态
    RefreshViewStylePulling, // 超过临界点
    RefreshViewStyleLoad     // 正在刷新
};


@interface RefreshView : UIView



/** 刷新控件状态 */
@property (nonatomic, assign) RefreshViewStyle refreshStyle;

/** 状态变化临界值 */
@property (nonatomic, assign) CGFloat refreshOffset;

/** 开始 */
-(void)startAnimation:(void(^)(void))start;

/** 移除 */
-(void)removeAnimation;


/**
 刷新控件设置

 @param scrollY 下拉值
 @param isDragging 是否正在拖拽
 @param load 加载刷新
 */
-(void)contentOffsetY:(CGFloat)scrollY withDragging:(BOOL)isDragging isStyleLoad:(void(^)(void))load;

@end

RefreshView.m文件

#import "RefreshView.h"

#define kWidth [UIScreen mainScreen].bounds.size.width

@interface RefreshView ()

/** 图形变化 */
@property (nonatomic, strong) UIImageView *imgView;

/** 设置加载位置 */
@property (nonatomic, assign) CGRect loadFrame;

@end


@implementation RefreshView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.loadFrame = frame;
        
        self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        self.imgView.contentMode = UIViewContentModeScaleAspectFit;
        self.imgView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
        
        [self addSubview:self.imgView];
     
    }
    return self;
}

-(void)setRefreshStyle:(RefreshViewStyle)refreshStyle{
    
    if (_refreshStyle != refreshStyle) {
        _refreshStyle = refreshStyle;
    }
    // 根据控件状态 设置图片
    switch (refreshStyle) {
            
        case RefreshViewStyleNormal:
            {
                self.imgView.image = [UIImage imageNamed:@"arrow.png"];
                [UIView animateWithDuration:0.2 animations:^{
                    self.imgView.transform = CGAffineTransformIdentity;
                }];
            }
            break;
            
        case RefreshViewStylePulling:
            {
                self.imgView.image = [UIImage imageNamed:@"arrow.png"];
                [UIView animateWithDuration:0.2 animations:^{
                    self.imgView.transform = CGAffineTransformMakeRotation(M_PI);
                }];
            }
            break;
            
        case RefreshViewStyleLoad:
            {
                self.imgView.image = [UIImage imageNamed:@"quan.png"];
            }
            break;

    }
    
    
    
}



/** 开始 */
-(void)startAnimation:(void(^)(void))start{
    
    
    if (![self.imgView.layer.animationKeys containsObject:@"rotationAnimation"]) {
    
        CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotationAnimation.fromValue = [NSNumber numberWithInt:0];
        rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
        rotationAnimation.duration = 0.7;
        rotationAnimation.repeatCount = HUGE_VALF;
        
        rotationAnimation.cumulative = YES;
        // 切换界面 animationKeys 清空了 需要设置removedOnCompletion = NO;
        rotationAnimation.removedOnCompletion = NO;
        rotationAnimation.fillMode = kCAFillModeForwards;
        
        [self.imgView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
        
        start();

    }
}

/** 移除 */
-(void)removeAnimation{

    if ([self.imgView.layer.animationKeys containsObject:@"rotationAnimation"]) {
    
        [UIView animateWithDuration:0.7 animations:^{
            
            self.alpha = 0;
            
        } completion:^(BOOL finished) {
            
            self.frame = CGRectMake((kWidth - self.loadFrame.size.width) / 2, -self.loadFrame.size.height, self.loadFrame.size.width, self.loadFrame.size.height);
            
            self.alpha = 1;
            
            // 手动释放
            [self.imgView.layer removeAnimationForKey:@"rotationAnimation"];
            
            self.refreshStyle = RefreshViewStyleNormal;
            
        }];
    }
    
}


//3 刷新控件设置
-(void)contentOffsetY:(CGFloat)scrollY withDragging:(BOOL)isDragging isStyleLoad:(void(^)(void))load{
    
    // 3.0 如何不是下拉操作 直接返回
    if (scrollY < 0) {
        return;
    }
    
    // 3.1 除正在刷新, 其余情况 高度跟随变化
    if (self.refreshStyle != RefreshViewStyleLoad) {
        
        self.frame = CGRectMake(self.loadFrame.origin.x, scrollY - self.loadFrame.size.height, self.loadFrame.size.width, self.loadFrame.size.height);
        
    }
    
    
    if (isDragging) { // 3.2 正在拉拽
        
        if (scrollY >= self.refreshOffset  && self.refreshStyle == RefreshViewStyleNormal) {
            
            // 拉拽超过临界点, 修改状态为[临界拉拽]
            self.refreshStyle = RefreshViewStylePulling;
            
        }else if (scrollY < self.refreshOffset  && self.refreshStyle == RefreshViewStylePulling){
            
            // 拉拽小于临界点, 修改状态为[正常]
            self.refreshStyle = RefreshViewStyleNormal;
        }
        
        
    } else { // 3.3 未处于拉拽状态, 并且状态为[临界拉拽]
        
        if (self.refreshStyle == RefreshViewStylePulling) {
            
            self.refreshStyle = RefreshViewStyleLoad;
            
            [UIView animateWithDuration:0.2 animations:^{
                self.frame = self.loadFrame;
            }];
            // 刷新界面
            [self startAnimation:^{
                
                load();
            }];
            
        }
        
    }
   
}

@end

二. 使用

#import "ViewController.h"
#import "RefreshView.h"

#define kWidth [UIScreen mainScreen].bounds.size.width
#define kHeight [UIScreen mainScreen].bounds.size.height

static CGFloat HeaderViewHegiht = 150.0;


@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *headerView;

// 刷新控件
@property (nonatomic, strong) RefreshView *refreshView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = [UIColor blackColor];
    
    // 0.1 创建TableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 50;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    // 0.2 向下偏移150
    self.tableView.contentInset = UIEdgeInsetsMake(HeaderViewHegiht, 0, 0, 0);
    
    // 0.3 添加顶部视图
    self.headerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -HeaderViewHegiht, kWidth, HeaderViewHegiht)];
    self.headerView.image = [UIImage imageNamed:@"huanghun.jpg"];
    self.headerView.contentMode = UIViewContentModeScaleAspectFill;
    [self.tableView addSubview:self.headerView];
    
    
    [self creatRefreshView];
    
}



#pragma mark - 刷新控件
-(void)creatRefreshView{
    
    self.refreshView = [[RefreshView alloc] initWithFrame:CGRectMake((kWidth - 30) /2, 40, 30, 30)];
    [self.view insertSubview:self.refreshView aboveSubview:self.tableView];
    self.refreshView.refreshStyle = RefreshViewStyleLoad;
    self.refreshView.refreshOffset = 130.0;
    
    __weak typeof(self)weakSelf = self;
    [self.refreshView startAnimation:^{
        [weakSelf handleData];
    }];
    
}




- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //1 头部背景图拉伸形变
    if (scrollView.contentOffset.y < - HeaderViewHegiht) {

        CGRect newHeaderFrame = self.headerView.frame;
        newHeaderFrame.origin.y = scrollView.contentOffset.y;
        newHeaderFrame.size.height = - scrollView.contentOffset.y;
        self.headerView.frame = newHeaderFrame;

    }

    
    //2 刷新控件设置
    __weak typeof(self)weakSelf = self;
    
    CGFloat refreshOffsetY = -scrollView.contentOffset.y - HeaderViewHegiht;
    
    [self.refreshView contentOffsetY:refreshOffsetY withDragging:scrollView.isDragging isStyleLoad:^{
        [weakSelf handleData];
    }];
    
    
}

-(void)handleData{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       
        [self.refreshView removeAnimation];
        
    });
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 30;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"identifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
    cell.textLabel.text = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
    
    return cell;
}



@end

以上 !

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