iOS 自定義下拉刷新控件 —— 解決圖片拉伸與數(shù)據(jù)刷新沖突

前言

iOS 的下拉刷新用的最廣泛的應(yīng)該是 MJRefresh. 但是有時候不能滿足我們的特殊需求. 如下拉時候, 設(shè)置的圖片放大, 那么用該控件刷新就會有些問題. 今天作者 就簡單封裝一個 刷新控件, 僅為各位提供個思路.

效果.gif

一. 控件

RefreshView.h文件

#import <UIKit/UIKit.h>

typedef NS_ENUM(NSInteger, RefreshViewStyle) {
    RefreshViewStyleNormal,  // 普通狀態(tài)
    RefreshViewStylePulling, // 超過臨界點
    RefreshViewStyleLoad     // 正在刷新
};


@interface RefreshView : UIView



/** 刷新控件狀態(tài) */
@property (nonatomic, assign) RefreshViewStyle refreshStyle;

/** 狀態(tài)變化臨界值 */
@property (nonatomic, assign) CGFloat refreshOffset;

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

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


/**
 刷新控件設(shè)置

 @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;

/** 設(shè)置加載位置 */
@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;
    }
    // 根據(jù)控件狀態(tài) 設(shè)置圖片
    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 清空了 需要設(shè)置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 刷新控件設(shè)置
-(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) {
            
            // 拉拽超過臨界點, 修改狀態(tài)為[臨界拉拽]
            self.refreshStyle = RefreshViewStylePulling;
            
        }else if (scrollY < self.refreshOffset  && self.refreshStyle == RefreshViewStylePulling){
            
            // 拉拽小于臨界點, 修改狀態(tài)為[正常]
            self.refreshStyle = RefreshViewStyleNormal;
        }
        
        
    } else { // 3.3 未處于拉拽狀態(tài), 并且狀態(tài)為[臨界拉拽]
        
        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 創(chuàng)建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 刷新控件設(shè)置
    __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

以上 !

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末古毛,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖锄贼,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件纲堵,死亡現(xiàn)場離奇詭異雷猪,居然都是意外死亡票从,警方通過查閱死者的電腦和手機(jī)吹零,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進(jìn)店門罩抗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人灿椅,你說我怎么就攤上這事套蒂。” “怎么了茫蛹?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵操刀,是天一觀的道長。 經(jīng)常有香客問我婴洼,道長骨坑,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任柬采,我火速辦了婚禮欢唾,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘粉捻。我一直安慰自己礁遣,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布肩刃。 她就那樣靜靜地躺著祟霍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪盈包。 梳的紋絲不亂的頭發(fā)上沸呐,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天,我揣著相機(jī)與錄音续语,去河邊找鬼垂谢。 笑死,一個胖子當(dāng)著我的面吹牛疮茄,可吹牛的內(nèi)容都是我干的滥朱。 我是一名探鬼主播,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼力试,長吁一口氣:“原來是場噩夢啊……” “哼徙邻!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起畸裳,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤缰犁,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體帅容,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡颇象,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了并徘。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片遣钳。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖麦乞,靈堂內(nèi)的尸體忽然破棺而出蕴茴,到底是詐尸還是另有隱情,我是刑警寧澤姐直,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布倦淀,位于F島的核電站,受9級特大地震影響声畏,放射性物質(zhì)發(fā)生泄漏撞叽。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一砰识、第九天 我趴在偏房一處隱蔽的房頂上張望能扒。 院中可真熱鬧,春花似錦辫狼、人聲如沸初斑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽见秤。三九已至,卻和暖如春真椿,著一層夾襖步出監(jiān)牢的瞬間鹃答,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工突硝, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留测摔,地道東北人。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓解恰,卻偏偏與公主長得像锋八,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子护盈,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,611評論 2 353