您好,登錄后才能下訂單哦!
iOS中怎么實現一個下拉、上拉刷新控件,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
控制器ViewController:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @end /*** ---------------分割線--------------- ***/ #import "ViewController.h" #import "HWRefresh.h" @interface ViewController ()<UITableViewDataSource, UITableViewDelegate> @property (nonatomic, strong) NSMutableArray *array; @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, assign) NSInteger page; @end @implementation ViewController - (NSMutableArray *)array { if (!_array) { _array = [NSMutableArray array]; } return _array; } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor blackColor]; self.page = 1; //模擬獲取信息 [self getInfo]; //創建控件 [self creatControl]; //添加頭部刷新 [self addHeaderRefresh]; //添加尾部刷新 [self addFooterRefresh]; } - (void)getInfo { NSArray *array = @[@"iOS HERO博客", @"iOS HERO博客", @"iOS HERO博客", @"iOS HERO博客", @"http://blog.csdn.net/hero_wqb"]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if (self.page == 1) { self.array = [NSMutableArray arrayWithArray:array]; }else{ [self.array addObjectsFromArray:array]; } [_tableView reloadData]; [_tableView headerEndRefreshing]; [_tableView footerEndRefreshing]; NSLog(@"已經刷新好了"); }); } - (void)creatControl { //列表視圖 _tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 64, [[UIScreen mainScreen] bounds].size.width - 100, [[UIScreen mainScreen] bounds].size.height - 164) style:UITableViewStylePlain]; _tableView.dataSource = self; _tableView.delegate = self; [self.view addSubview:_tableView]; } - (void)addHeaderRefresh { __weak typeof(self) weakSelf = self; [_tableView addHeaderRefreshWithCallback:^{ __strong typeof(weakSelf) strongSelf = weakSelf; strongSelf.page = 1; [strongSelf getInfo]; }]; } - (void)addFooterRefresh { __weak typeof(self) weakSelf = self; [_tableView addFooterRefreshWithCallback:^{ __strong typeof(weakSelf) strongSelf = weakSelf; strongSelf.page ++; [strongSelf getInfo]; }]; } #pragma mark - UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.array.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"refreshTest"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; } cell.textLabel.text = [_array[indexPath.row] stringByAppendingString:[NSString stringWithFormat:@"_%ld", indexPath.row]]; return cell; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { //滑動到底部自動刷新 if (_tableView.contentSize.height > _tableView.frame.size.height && _tableView.contentOffset.y + _tableView.frame.size.height > _tableView.contentSize.height - 40 && _page < 50) { [_tableView footerBeginRefreshing]; } } @end
刷新基類HWRefreshBaseView:
#import <UIKit/UIKit.h> #define HWRefreshContentOffset @"contentOffset" typedef enum { HWRefreshStateNormal = 0, //普通狀態 HWRefreshStatePulling, //釋放即可刷新的狀態 HWRefreshStateRefreshing, //正在刷新中的狀態 } HWRefreshState; @interface HWRefreshBaseView : UIView @property (nonatomic, weak) UIScrollView *scrollView; @property (nonatomic, copy) NSString *pullToRefreshText; @property (nonatomic, copy) NSString *releaseToRefreshText; @property (nonatomic, copy) NSString *refreshingText; @property (nonatomic, copy) void (^refreshingCallback)(); @property (nonatomic, assign) HWRefreshState state; @property (nonatomic, assign) UIEdgeInsets scrollViewOriginalInset; - (void)beginRefreshing; - (void)endRefreshing; @end /*** ---------------分割線--------------- ***/ #import "HWRefreshBaseView.h" #define KHWRefreshViewHeight 44.0f #define KImageW 30.0f #define KLabelW 100.0f @interface HWRefreshBaseView () @property (nonatomic, weak) UILabel *rLabel; @property (nonatomic, weak) UIImageView *rImageView; @end @implementation HWRefreshBaseView - (instancetype)initWithFrame:(CGRect)frame { frame.size.height = KHWRefreshViewHeight; if (self = [super initWithFrame:frame]) { CGFloat imageH = 30.f; CGFloat labelH = 20.f; CGFloat imageX = ([UIScreen mainScreen].bounds.size.width - KImageW - KLabelW) * 0.5; CGFloat imageY = (KHWRefreshViewHeight - imageH) * 0.5; CGFloat labelY = (KHWRefreshViewHeight - labelH) * 0.5; //圖片 UIImageView *rImageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, KImageW, imageH)]; rImageView.image = [UIImage imageNamed:@"refreshing.jpg"]; [self addSubview:rImageView]; self.rImageView = rImageView; //標簽 UILabel *rLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(rImageView.frame), labelY, KLabelW, labelH)]; rLabel.text = self.pullToRefreshText; rLabel.font = [UIFont systemFontOfSize:14.0f]; rLabel.textAlignment = NSTextAlignmentCenter; [self addSubview:rLabel]; self.rLabel = rLabel; } return self; } - (void)willMoveToSuperview:(UIView *)newSuperview { [super willMoveToSuperview:newSuperview]; //舊的父控件 [self.superview removeObserver:self forKeyPath:HWRefreshContentOffset context:nil]; //新的父控件 if (newSuperview) { [newSuperview addObserver:self forKeyPath:HWRefreshContentOffset options:NSKeyValueObservingOptionNew context:nil]; //記錄UIScrollView _scrollView = (UIScrollView *)newSuperview; //記錄UIScrollView最開始的contentInset _scrollViewOriginalInset = _scrollView.contentInset; } //居中顯示圖片、提示信息 CGRect temFrame = _rImageView.frame; temFrame.origin.x = (newSuperview.frame.size.width - KImageW - KLabelW) * 0.5; _rImageView.frame = temFrame; CGRect tf = _rLabel.frame; tf.origin.x = CGRectGetMaxX(_rImageView.frame); _rLabel.frame = tf; } - (void)setPullToRefreshText:(NSString *)pullToRefreshText { _pullToRefreshText = pullToRefreshText; self.rLabel.text = pullToRefreshText; } - (void)setState:(HWRefreshState)state { if (_state == state) return; switch (state) { case HWRefreshStateNormal: { [self stopAnimating]; self.rLabel.text = self.pullToRefreshText; break; } case HWRefreshStatePulling: { self.rLabel.text = self.releaseToRefreshText; break; } case HWRefreshStateRefreshing: { [self startAnimating]; self.rLabel.text = self.refreshingText; if (self.refreshingCallback) self.refreshingCallback(); break; } default: break; } _state = state; } //開始刷新 - (void)beginRefreshing { self.state = HWRefreshStateRefreshing; } //結束刷新 - (void)endRefreshing { self.state = HWRefreshStateNormal; } //開始動畫 - (void)startAnimating { NSMutableArray *array = [NSMutableArray array]; for (int i = 0; i < 2; i++) { NSString *imageName = [NSString stringWithFormat:@"refreshing%02d.jpg", i + 1]; UIImage *image = [UIImage imageNamed:imageName]; [array addObject:image]; } [_rImageView setAnimationImages:array]; [_rImageView setAnimationDuration:0.3f]; [_rImageView startAnimating]; } //結束動畫 - (void)stopAnimating { if (_rImageView.isAnimating) { [_rImageView stopAnimating]; [_rImageView performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:0]; } } @end
頭部刷新HWRefreshHeader:
#import "HWRefreshBaseView.h" @interface HWRefreshHeader : HWRefreshBaseView + (instancetype)header; @end /*** ---------------分割線--------------- ***/ #import "HWRefreshHeader.h" @implementation HWRefreshHeader + (instancetype)header { return [[HWRefreshHeader alloc] init]; } - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { self.pullToRefreshText = @"下拉即可刷新"; self.releaseToRefreshText = @"釋放即可刷新"; self.refreshingText = @"刷新中..."; } return self; } - (void)willMoveToSuperview:(UIView *)newSuperview { [super willMoveToSuperview:newSuperview]; //設置自己的位置和尺寸 CGRect frame = self.frame; frame.origin.y = - self.frame.size.height; self.frame = frame; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { //不能跟用戶交互或正在刷新就直接返回 if (!self.userInteractionEnabled || self.alpha <= 0.01 || self.hidden || self.state == HWRefreshStateRefreshing) return; //根據偏移量設置相應狀態 if ([keyPath isEqualToString:HWRefreshContentOffset]) { [self setStateWithContentOffset]; } } - (void)setStateWithContentOffset { //當前的contentOffset CGFloat currentOffsetY = self.scrollView.contentOffset.y; //頭部控件剛好出現的offsetY CGFloat happenOffsetY = - self.scrollViewOriginalInset.top; //如果是向上滾動到看不見頭部控件,直接返回 if (currentOffsetY >= happenOffsetY) return; //滑動時 if (self.scrollView.isDragging) { //普通狀態和即將刷新狀態的臨界點 CGFloat normalTopullingOffsetY = happenOffsetY - self.frame.size.height; //轉為即將刷新狀態 if (self.state == HWRefreshStateNormal && currentOffsetY < normalTopullingOffsetY) { self.state = HWRefreshStatePulling; //轉為普通狀態 }else if (self.state == HWRefreshStatePulling && currentOffsetY >= normalTopullingOffsetY) { self.state = HWRefreshStateNormal; } //松手時,如果是松開就可以進行刷新的狀態,則進行刷新 }else if (self.state == HWRefreshStatePulling) { self.state = HWRefreshStateRefreshing; } } - (void)setState:(HWRefreshState)state { //若狀態未改變,直接返回 if (self.state == state) return; //保存舊狀態 HWRefreshState oldState = self.state; //調用父類方法 [super setState:state]; switch (state) { case HWRefreshStateNormal: { //如果由刷新狀態返回到普通狀態 if (oldState == HWRefreshStateRefreshing) { [UIView animateWithDuration:0.25f animations:^{ UIEdgeInsets inset = self.scrollView.contentInset; inset.top -= self.frame.size.height; self.scrollView.contentInset = inset; }]; } break; } case HWRefreshStatePulling: { break; } case HWRefreshStateRefreshing: { //執行動畫 [UIView animateWithDuration:0.25f animations:^{ CGFloat top = self.scrollViewOriginalInset.top + self.frame.size.height; //增加滾動區域 UIEdgeInsets inset = self.scrollView.contentInset; inset.top = top; self.scrollView.contentInset = inset; //設置滾動位置 CGPoint offset = self.scrollView.contentOffset; offset.y = - top; self.scrollView.contentOffset = offset; }]; break; } default: break; } self.state = state; } @end
分類UIScrollView+HWRefresh:
#import <UIKit/UIKit.h> @interface UIScrollView (HWRefresh) //添加下拉刷新回調 - (void)addHeaderRefreshWithCallback:(void (^)())callback; //讓下拉刷新控件停止刷新 - (void)headerEndRefreshing; //添加上拉刷新回調 - (void)addFooterRefreshWithCallback:(void (^)())callback; //讓上拉刷新控件開始刷新 - (void)footerBeginRefreshing; //讓上拉刷新控件停止刷新 - (void)footerEndRefreshing; @end /*** ---------------分割線--------------- ***/ #import "UIScrollView+HWRefresh.h" #import "HWRefreshHeader.h" #import "HWRefreshFooter.h" #import <objc/runtime.h> @interface UIScrollView () @property (nonatomic, weak) HWRefreshHeader *header; @property (weak, nonatomic) HWRefreshFooter *footer; @end @implementation UIScrollView (HWRefresh) static char HWRefreshHeaderKey; static char HWRefreshFooterKey; - (void)setHeader:(HWRefreshHeader *)header { [self willChangeValueForKey:@"HWRefreshHeaderKey"]; objc_setAssociatedObject(self, &HWRefreshHeaderKey, header, OBJC_ASSOCIATION_ASSIGN); [self didChangeValueForKey:@"HWRefreshHeaderKey"]; } - (HWRefreshHeader *)header { return objc_getAssociatedObject(self, &HWRefreshHeaderKey); } - (void)setFooter:(HWRefreshFooter *)footer { [self willChangeValueForKey:@"HWRefreshFooterKey"]; objc_setAssociatedObject(self, &HWRefreshFooterKey, footer, OBJC_ASSOCIATION_ASSIGN); [self didChangeValueForKey:@"HWRefreshFooterKey"]; } - (HWRefreshFooter *)footer { return objc_getAssociatedObject(self, &HWRefreshFooterKey); } - (void)addHeaderRefreshWithCallback:(void (^)())callback { if (!self.header) { HWRefreshHeader *header = [HWRefreshHeader header]; [self addSubview:header]; self.header = header; } self.header.refreshingCallback = callback; } - (void)headerEndRefreshing { [self.header endRefreshing]; } - (void)addFooterRefreshWithCallback:(void (^)())callback { if (!self.footer) { HWRefreshFooter *footer = [HWRefreshFooter footer]; [self addSubview:footer]; self.footer = footer; } self.footer.refreshingCallback = callback; } - (void)footerBeginRefreshing { [self.footer beginRefreshing]; } - (void)footerEndRefreshing { [self.footer endRefreshing]; } @end
看完上述內容,你們掌握iOS中怎么實現一個下拉、上拉刷新控件的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。