Use UIRefreshControl without extending UITableViewController

Apple在iOS 6推出UIRefreshControl,替開發者解決最常用的下拉刷新效果。雖然網路上幾個third-party libraries真的不錯,像SVPullToRefresh幾行程式碼就可以辦到,但可惜久沒更新,畫面呈現實在不合我需求,來試試看原生的UIRefreshControl吧

實際用法很簡單,可以參考這篇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 {
    // 取資料
}

沒有留言: