//
//  UIScrollView+LPRefresh.m
//  LPRefresh
//
//  Created by FineexMac on 16/3/2.
//  Copyright 漏 2016骞?LPiOS. All rights reserved.
//
//  浣滆€匞itHub涓婚〉 https://github.com/SwiftLiu
//  浣滆€呴偖绠?1062014109@qq.com
//  涓嬭浇閾炬帴 https://github.com/SwiftLiu/LPRefresh.git

#import "LPRefresh.h"
#import <objc/runtime.h>
#import "LPRefreshIndicator.h"

static NSString *KEY_PATH = @"contentOffset";

@implementation UIScrollView (LPRefresh)

#pragma mark - 灞炴€etter鍜宻etter鏂规硶(rumtime鏈哄埗)
static char LPRefreshIndicatorKey;
- (void)setIndicator:(LPRefreshIndicator *)indicator
{
    if (indicator != self.indicator) {
        [self.indicator removeFromSuperview];
        
        [self willChangeValueForKey:@"indicator"];
        objc_setAssociatedObject(self, &LPRefreshIndicatorKey,
                                 indicator,
                                 OBJC_ASSOCIATION_ASSIGN);
        [self didChangeValueForKey:@"indicator"];
        
        [self addSubview:indicator];
    }
}
- (LPRefreshIndicator *)indicator
{
    return objc_getAssociatedObject(self, &LPRefreshIndicatorKey);
}


#pragma mark - 閲嶅啓
- (void)setFrame:(CGRect)frame
{
    if (self.frame.size.width != frame.size.width) {
        [self centerSub:frame.size.width];
    }
    [super setFrame:frame];
}

- (void)setBounds:(CGRect)bounds
{
    if (self.bounds.size.width != bounds.size.width) {
        [self centerSub:bounds.size.width];
    }
    [super setBounds:bounds];
}
//indicator灞呬腑
- (void)centerSub:(CGFloat)width
{
    CGRect frame = self.indicator.frame;
    frame.size.width = width;
    frame.origin.x = (width - frame.size.width) / 2.l;
    self.indicator.frame = frame;
}


#pragma mark - 娣诲姞鍒锋柊浜嬩欢
- (void)addRefreshWithBlock:(void (^)())block
{
    self.delaysContentTouches = NO;
    
    //鍒锋柊涓讳欢
    self.indicator = [LPRefreshIndicator new];
    CGRect frame = self.indicator.frame;
    frame.origin.y = -frame.size.height;
    frame.size.width = self.bounds.size.width;
    self.indicator.frame = frame;
    self.indicator.refreshBlock = block;
    
    //娣诲姞瑙傚療鑰咃紝鐩戝惉contentOffset
    [self addObserver:self
           forKeyPath:KEY_PATH
              options:NSKeyValueObservingOptionNew
              context:nil];
}

- (void)didChangeValueForKey:(NSString *)key
{
    //涓嬫媺杩涘害
    if ([key isEqualToString:KEY_PATH] && self.contentOffset.y <= 0) {
        self.indicator.pullProgress = -self.contentOffset.y;
    }
}

//绉婚櫎瑙傚療鑰?- (void)dealloc
{
//    [self removeObserver:self forKeyPath:KEY_PATH context:nil];
}


#pragma mark - 缁撴潫鍒锋柊
- (void)endRefreshingSuccess
{
    [self.indicator refreshSuccess:YES];
}

- (void)endRefreshingFail
{
    [self.indicator refreshSuccess:NO];
}

@end
// 鐗堟潈灞炰簬鍘熶綔鑰?// http://code4app.com (cn) http://code4app.net (en)
// 鍙戝竷浠g爜浜庢渶涓撲笟鐨勬簮鐮佸垎浜綉绔? Code4App.com