Thursday, September 17, 2015

Pull To Refresh Tutorial


Hi all,

I have heard and seen this feature many a times while browsing through apps.
Liked it very much.

So i decided why not to try out this feature and share my experience with you all.
Hope somebody finds help with this.

Lets start....


1) Create a Project "Single View Application"



2) Set a product name : PullToRefresh


3)  Open the storyboard file and add UITableView to the provided view

Connect TableView Outlets, Delegates and Datasources


4) Under UITableView add UITableViewCell. 

This is a Static cell with Identifier as "CellIdentifier" and with only "Title" property.


5) Now comes the Controller part

5.1) Open ViewController.h and add properties for


@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
{
    
}

@property(nonatomic, strong)IBOutlet UITableView   *dataTable;
@property(nonatomic, strong)NSArray                        *fruitsArray;
@property(nonatomic, strong)UIRefreshControl          *refreshControl;

@end


5.2) Open ViewController.m and make dough from ingredients :P


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.fruitsArray = [[NSArray alloc] initWithObjects:
                                 @"Apple", @"Orange", @"Mango" , @"Grapes", @"Banana", nil];
    
    self.refreshControl = [[UIRefreshControl alloc] init];

    [self.refreshControl addTarget:self
                                           action:@selector(refreshControlValueChanged) 
                         forControlEvents:UIControlEventValueChanged];

    self.refreshControl.tintColor = [UIColor redColor];

    [self.dataTable addSubview:self.refreshControl];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;

}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.fruitsArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier" 
                                                                   forIndexPath:indexPath];
    
    cell.textLabel.text          = self.fruitsArray[indexPath.row];
    cell.textLabel.textColor = [UIColor blueColor];

    return cell;

}



- (void)refreshControlValueChanged
{
    self.fruitsArray = [self.fruitsArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    
    [self performSelector:@selector(updateTable)
                     withObject:nil
                      afterDelay:1];
}



- (void)updateTable
{
    [self.dataTable reloadData];
    
    [self.refreshControl endRefreshing];
}


6) Now run your App and see a list of fruits that are not sorted.



7) Drag your table & see the spinning wheel


8) Now see the refreshed data...



Happy Coding....
Enjoy :)




4 comments: