Daniel Robinson Daniel Robinson - 3 months ago 69
Objective-C Question

Pull to refresh UITableView without UITableViewController

I'm trying to implement a pull to refresh feature in a UITableView within a UIViewController. I can't use a UITableViewController because I want the UITableView to be a smaller subview in the view controller, with some other stuff above it. I assume this is possible, but has anyone seen an implementation of it?

Answer

To add a refresh control directly to a UITableView without using a UITableViewController, use this code:

Swift

override func viewDidLoad() {
    super.viewDidLoad()
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: "refresh:", forControlEvents: .ValueChanged)
    tableView.addSubview(refreshControl)
}

func refresh(refreshControl: UIRefreshControl) {
    // Do your job, when done:
    refreshControl.endRefreshing()
}

Objective-C

- (void)viewDidLoad {
    [super viewDidLoad];
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:refreshControl];
}

- (void)refresh:(UIRefreshControl *)refreshControl {
    // Do your job, when done:
    [refreshControl endRefreshing];
}

Note: UIRefreshControl is added in iOS6

Comments