Wednesday, February 17, 2016

Objective C UITableView Pull To Refresh

We display list data in table views usually. Before or after navigating to this list view we call the respective service, parse data and display that in the list view.

So when this data will get refreshed? What If a bunch of changes occurred in the server database in a short span of time and our app is still displaying the old data. In this case we can provide the below features to get latest content from server through service calls.


  • Keeping a Refresh button on the view, on clicking which, we call the service again and display the latest data.
  • Running a timer and fetching the data for regular time interval.


However, these two ways solve the things, but they are not user friendly.


                         



The best way is to keep some thing like user pulls the list view and content gets refreshed like in the Facebook feed post in our devices. This we call it as 'Pull To Refresh'. 

In objective C we have UIRefreshControl to implement this functionality. Below is the piece of code for applying pull to refresh functionality to a UITableView.




    UITableView *tableView = [UITableView alloc] init];

    UIRefreshControl *refreshControl = [[UIRefreshControl allocinit];

    refreshControl.tintColor = [UIColor blackColor];
    
    [refreshControl addTarget:self action:@selector(reloadDataFromRefresh)  
          forControlEvents:UIControlEventValueChanged];
    
    NSMutableAttributedString *refreshString = [[NSMutableAttributedString alloc
                                                                           initWithString:@"Pull To Refresh"];

    [refreshString addAttributes:@{NSForegroundColorAttributeName : [UIColor    
                                       blackColor]} range:NSMakeRange(0, refreshString.length)];

    refreshControl.attributedTitle = refreshString;

    tableView.refreshControl = refreshControl;



In the above code I have taken a UIRefreshControl object and assigned it to the tableview's refreshControl. We can customize the color of refresh loader and the refresh text we want to display when the user pulls our table view.


Hope this post is useful. Feel free to comment in case of any queries.