Friday, April 4, 2014

Working with UIRefreshControl





             The class reference of UIRefreshControl is short, hinting at how easy it is to get started with this addition of the UIKit framework. The UIRefreshControl class directly descends from UIControl, which means that setting up an instance ofUIRefreshControl is not much different from creating and configuring any other UIKit control. After instantiating an instance of the UIRefreshControl class, you assign it to the new refreshControl property of a table view controller object (UITableViewController or a subclass of it). The table view controller takes care of properly positioning and displaying the refresh control. As with any otherUIControl subclass, you attach a target-action pair to a specific event,UIControlEventValueChanged in the case of UIRefreshControl.

      If you run the application in the iPhone Simulator, you should see an empty table view. Take a look at the implementation of the viewDidLoad method shown below. We initialize the refresh control and add a target and action for the UIControlEventValueChangedevent of the refresh control. Finally, the refresh control is assigned to therefreshControl property of the table view controller. Of course, therefreshControl property is also new for iOS 6.



- (void)viewDidLoad {
    [super viewDidLoad];
    // Initialize Refresh Control
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    // Configure Refresh Control
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    // Configure View Controller
    [self setRefreshControl:refreshControl];
}



Before we build and run the project once more, we need to implement therefresh: action in the view controller's implementation file. The idea behind the refresh control is in some ways similar to UIKit's activity indicator view (UIActivityIndicatorView), that is, you are responsible for showing and hiding it. Hiding the refresh control is as simple as sending it a message ofendRefreshing



- (void)refresh:(id)sender
{
    NSLog(@"Refreshing");

// End Refreshing
    [(UIRefreshControl *)sender endRefreshing];
}



There are many libraries that try to mimic the original "pull to refresh" functionality, but it is nice to see that Apple has finally embraced this neat concept and included it in the UIKit framework.

No comments:

Post a Comment