使用UIRefreshControl实现下拉刷新

UIRefreshControl 为 UITableViewController 中的一个属性,从以下可以看出, IOS6.0 以上才支持。

NS_CLASS_AVAILABLE_IOS(6_0) __TVOS_PROHIBITED @interface UIRefreshControl : UIControl

具体实现代码如下:
ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UITableViewController

@end

ViewController.m

#import "ViewController.h"

#define RandomData [NSString stringWithFormat:@"随机数据---%d", arc4random_uniform(1000000)]

@interface ViewController ()

@property (nonatomic,strong) NSMutableArray *dataArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化数据源
    _dataArray = [[NSMutableArray alloc] init];
    
    for (int i = 0; i<3; i++) {
        [self.dataArray addObject:RandomData];
    }
    
    //初始化refreshControl
    self.refreshControl = [[UIRefreshControl alloc] init];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
    [self.refreshControl addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventValueChanged];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@", indexPath.row % 2?@"push":@"modal", self.dataArray[indexPath.row]];
    return cell;
}


- (void)refreshData{
    // 1.添加数据
    for (int i = 0; i<5; i++) {
        [self.dataArray addObject:RandomData];
    }
    // 2.模拟2秒后刷新表格UI
    __weak __typeof(self)wself = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        __strong __typeof (wself) sself = wself;
        
        //结束刷新(重要,只有先处理完了数据源,再执行方法 endRefreshing 让tableView回去)
        [sself.refreshControl endRefreshing];
        
        //重新加载
        [sself.tableView reloadData];
    });
}

@end

Demo地址

转载于:https://www.cnblogs.com/allen12/p/9755505.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值