原來UIScrollView自帶了一個下拉刷新的控件。但是并不是那么好用辅甥,于是做了一些封裝狡忙。
UIRefreshControl:
發(fā)現(xiàn)UIRefreshControl 很簡潔,
- refreshing 一個狀態(tài)屬性
- tintColor 一個菊花圈圈的顏色
- attributedTitle 一個刷新時顯示的文字
- -(void) beginRefreshing 開始刷新, 根據(jù)偏移量 會自動進入刷新弓叛。
- -(void) endRefreshing 結(jié)束刷新彰居,必須自己調(diào)用
不難發(fā)現(xiàn)這邊少了一個開始刷新的回調(diào)。簡單一點的我們可以這么做:
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
if (self.refresh.isRefreshing) {
NSLog(@"開始刷新了??");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.refresh endRefreshing];
});
}
NSLog(@"y = %f , x = %f", scrollView.contentOffset.y, scrollView.contentOffset.x);
}
但是每次都去寫一個代理撰筷,看起來并不是那么友好啊陈惰。所以有了下面的事情:
#import "UIScrollView+LJRefresh.h"
#import <objc/runtime.h>
@interface UIScrollView ()
@property(nonatomic, strong)void(^refreshHandler)();
@end
@implementation UIScrollView (LJRefresh)
+(void)load{
Method originalMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"handlePan:"));
Method swizzledMethod = class_getInstanceMethod([self class], @selector(customPanGesture:));
method_exchangeImplementations(originalMethod, swizzledMethod);
}
static char refreshBlockKey;
-(void (^)())refreshHandler{
return objc_getAssociatedObject(self, &refreshBlockKey);
}
-(void)setRefreshHandler:(void (^)())refreshHandler{
objc_setAssociatedObject(self, &refreshBlockKey, refreshHandler, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)addSystemHeadRefresh:(NSString *)title handler:(void (^)())handler{
UIRefreshControl* refresh = [[UIRefreshControl alloc]init];
NSAttributedString* attributeStr = [[NSAttributedString alloc]initWithString:title];
refresh.attributedTitle = attributeStr;
refresh.tintColor = [UIColor redColor];
self.refreshControl = refresh;
self.refreshHandler = handler;
}
-(void)customPanGesture:(UIPanGestureRecognizer *)gestureRecognizer{
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
if (self.refreshControl.isRefreshing && self.refreshHandler) {
self.refreshHandler();
}
}
[self customPanGesture:gestureRecognizer];
}
-(void)beginSystemHeadRefresh{
[self.refreshControl beginRefreshing];
}
-(void)endSystemHeadRefresh{
[self.refreshControl endRefreshing];
}
@end
沒錯,就是寫個UIScrollView的分類毕籽,再把ScrollView上面原來的Pan手勢的Action 用黑魔法轉(zhuǎn)換抬闯,再監(jiān)聽手勢結(jié)束后的狀態(tài)。就是我們需要的開始刷新狀態(tài)了关筒。
使用的時候 就這么著:
@weakify(self);
[self.contentScrollView addSystemHeadRefresh:@"??????hello" handler:^{
@strongify(self);
DLog(@" 開始刷新啦`````");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.35*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.contentScrollView endSystemHeadRefresh];
});
}];
refresh.gif