UIRefreshControl的使用非常简单。
1、使用范围
如果你装了xcode_4.5_developer_preview,那么在UITableViewController.h文件中你会看到,UITableViewController里面有如下声明,说明UITableViewController已经内置了UIRefreshControl控件
- @property (nonatomic,retain) UIRefreshControl *refreshControl NS_AVAILABLE_IOS(6_0);
a)初始化
如何在UITableViewController 中使用UIRefreshControl呢,在上面给出的代码附件中,你可以很详细的知道,这里介绍一下关键的部分:
- self.refreshControl = [[UIRefreshControl alloc]init];
- // self.refreshControl.tintColor = [UIColor blueColor];
- self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
- [self.refreshControl addTarget:self action:@selector(RefreshViewControlEventValueChanged) forControlEvents:UIControlEventValueChanged];
如上面看到的代码,虽然UITableViewController已经声明了UIRefreshControl,但是貌似还没有初始化,所以需要我们自己初始化。很神奇,初始化的时候并不需要给它指定frame,UITableViewController会为我们进行管理。遗憾的时目前只看到下拉刷新功能,上拉刷新还没有,估计在最终版里面苹果会考虑加入上拉刷新功能。
我们还可以给UIRefreshControl设置tintColor和attributedTitle。
b)下拉刷新事件监听
当用户进行下拉刷新操作时,UIRefreshControl 会触发一个UIControlEventValueChanged事件,通过监听这个事件,我们就可以进行类似数据请求的操作了。如下代码:
[self.refreshControl addTarget:self action:@selector(RefreshViewControlEventValueChanged)
c)进行数据请求
在示例中,为了演示数据请求,我简单的做了一个延时处理,2秒钟后,调用handleData
- [self performSelector:@selector(handleData) withObject:nil afterDelay:2];
- - (void) handleData
- {
- NSLog(@"refreshed");
- [self.refreshControl endRefreshing];
- self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
- self.count++;
- [self.tableView reloadData];
- }
3、官方头文件
下面是sdk中UIRefreshControl的声明,想必看了下面的代码,你已经知道如何使用了 。
- //
- // UIRefreshControl.h
- // UIKit
- //
- // Copyright 2012 Apple Inc. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- #import <UIKit/UIControl.h>
- #import <UIKit/UIKitDefines.h>
- NS_CLASS_AVAILABLE_IOS(6_0) @interface UIRefreshControl : UIControl
- /* The designated initializer
- * This initializes a UIRefreshControl with a default height and width.
- * Once assigned to a UITableViewController, the frame of the control is managed automatically.
- * When a user has pulled-to-refresh, the UIRefreshControl fires its UIControlEventValueChanged event.
- */
- - (id)init;
- @property (nonatomic, readonly, getter=isRefreshing) BOOL refreshing;
- @property (nonatomic, retain) UIColor *tintColor UI_APPEARANCE_SELECTOR;
- @property (nonatomic, retain) NSAttributedString *attributedTitle UI_APPEARANCE_SELECTOR;
- // May be used to indicate to the refreshControl that an external event has initiated the refresh action
- - (void)beginRefreshing NS_AVAILABLE_IOS(6_0);
- // Must be explicitly called when the refreshing has completed
- - (void)endRefreshing NS_AVAILABLE_IOS(6_0);
- @end
- self.refreshControl = [[UIRefreshControl alloc]init];
- // self.refreshControl.tintColor = [UIColor blueColor];
- self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
- [self.refreshControl addTarget:self action:@selector(RefreshViewControlEventValueChanged) forControlEvents:UIControlEventValueChanged];