實際用法很簡單,可以參考這篇iOS Programming 101: Implementing Pull-to-Refresh and Handling Empty Table
不過!網路上的教學都有個前提:使用UIRefreshControl的ViewController都必需繼承UITableViewController,也就是要長這樣
//MyViewController.h file
@interface MyViewController:UITableViewController
{
}
@end
這樣太不實際了,萬一舊專案在後期想要回頭使用UIRefreshControl,或是畫面本身非常複雜,豈不是要額外耗費時間去修改?!解決辦法很簡單,只要透過addSubview把UIRefreshControl加到你的table即可。實際程式碼如下
//MyViewController.h file
@interface MyViewController:UIViewController
{
@property(nonatomic, retain) UIRefreshControl *refreshControl;
@property (weak, nonatomic) IBOutlet UITableView *tbl;
}@end
//MyViewController.m file
@interface MyViewController ()
@end
@implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// get data
[self getMyData];
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
self.refreshControl.backgroundColor = [UIColor purpleColor];
self.refreshControl.tintColor = [UIColor whiteColor];
self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
[self.refreshControl addTarget:self
action:@selector(getMyData)
forControlEvents:UIControlEventValueChanged];
[self.tbl addSubview:self.refreshControl];
}
- (void) getMyData {
// 取資料
}