UIRefreshControl 实现UITableView的下拉刷新

来源:互联网 发布:挠脚心知不及格代价上 编辑:程序博客网 时间:2024/04/28 02:39

本文通过使用UITableView自带的控件UIRefreshControl实现下拉刷新。用UIRefeshControl控件实现下拉刷新,可以实现一定功能的自定义下拉菜单,比如要显示的文字、颜色。但这种方法简单,高效,容易理解,毕竟是apple自带的下拉刷新控件,

UITableViewController:

首先xcode创建一个UITableViewController
数据源:
@property (nonatomic, strong) NSMutableArray* dataArray;

在viewdidload方法中实现
- (void)viewDidLoad {    [super viewDidLoad];         //数据源初始化    _dataArray = [[NSMutableArray alloc] initWithObjects:[NSDate dateWithTimeIntervalSinceNow:0], [NSDate dateWithTimeIntervalSinceNow:1], [NSDate dateWithTimeIntervalSinceNow:2], nil];        UIRefreshControl  *refreshControl = [[UIRefreshControl alloc] init];        //设置refreshControl的属性    refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"loading..." attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:[UIColor greenColor]}];    refreshControl.tintColor = [UIColor redColor];        //为下拉菜单添加action    [self.refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];        //把refreshcontrol添加到自身。这样就可以实现下拉刷新了    self.refreshControl = refreshControl;    }

处理注册action的函数:
- (void) handleRefresh:(id)paramSender {    // 模拟2秒后刷新数据    int64_t delayInSeconds = 2.0f;    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){        //停止刷新        [self.refreshControl endRefreshing];        //tableview中插入一条数据        [self.dataArray addObject:[NSDate date]];        NSIndexPath *indexPathOfNewRow = [NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0];        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfNewRow, nil] withRowAnimation:UITableViewRowAnimationFade];    });}

tableview的Datasource代理函数

#pragma mark - Table view data source- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {    return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    return [_dataArray count];}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kIdentify];    if (!cell) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: kIdentify];    }        cell.textLabel.text = [self stringFromDate:_dataArray[indexPath.row]];        return cell;}

UIVIewController:


对于普通的ViewController也可以通过这种方式 实现下啦刷新。只是把UIRefreshControl变为要刷新table的子view就可以了

@interface GBViewController ()<UITableViewDelegate, UITableViewDataSource>@property (weak, nonatomic) IBOutlet UITableView *tableview;@property (nonatomic, strong) NSMutableArray* dataArray;@end
在viewDidLoad中

_tableview.delegate = self;[_tableview addSubview:refreshControl];

其余和在TableViewController中一样。运行结果:



0 0
原创粉丝点击