Wednesday, 3 August 2016

Implement Pull to refresh in UITableView in iOS using Objective C

Today we will learn how to give pull to refresh in tableView in iOS.

1. Create a new Xcode Project Lets say (PullToRefreshDemoTableView).
2.  Now go to StoryBoard and take a TableView and connect properties and delegate Methods.

3. Now go to Your View Controller.m and write the following code in Your ViewDidLoad.
#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;


@implementation ViewController{
     NSMutableArray *tableDataArray;

- (void)viewDidLoad {
    [super viewDidLoad];
    tableDataArray = [[NSMutableArray alloc]initWithObjects:@"Ram",@"Shyam",@"Mohan",@"nilesh", nil];
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:refreshControl];
    // Do any additional setup after loading the view, typically from a nib.
4. Now Write the dataSource and delgate method of tableView.

#pragma mark -  tableView Delagate Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [tableDataArray count];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    static NSString *simpleTableIdentifier = @"SimpleTableItem";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    cell.textLabel.text = [tableDataArray objectAtIndex:indexPath.row];
    return cell;

5. Define the Custom Method for refresh control.

#pragma mark -  Custom Methods

- (void)refresh:(UIRefreshControl *)refreshControl {
    // Do your job, when done:
    [tableDataArray addObject:@"Priya"];
    [_tableView reloadData];
    [refreshControl endRefreshing];

Now run the code and pull down the tableview to see the desired result.

You can download the whole source code from here.
Please have Your valuable feedback.
Enjoy Coding :)

No comments:

Post a Comment

Ads Inside Post

Blogger Widget