Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a pull to refresh for UIViewController instead of UITableViewController in swift?

Tags:

ios

swift

view

I've got a simple app that have no need to be constructed with UITableViewController. Is there any chance to create 'pull to refresh' functionality for the simple UIViewController?

like image 457
Nick Samoylov Avatar asked Apr 20 '16 14:04

Nick Samoylov


2 Answers

Yes, there is. In fact, in order to use UIRefreshControl there is only one requirement - you can place UIRefreshControl inside of UIScrollView or its subclass (for example UITableView or UICollectionView).

Example code in Swift:

override func viewDidLoad() {
{
    super.viewDidLoad()
    //...
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(didPullToRefresh), forControlEvents: .ValueChanged)

    scrollView.addSubview(refreshControl)
}

func didPullToRefresh() {

}

Example code in Objective-c:

- (void)viewDidLoad
{
    [super viewDidLoad];
    //...

    UIRefreshControl *refreshControl = [UIRefreshControl new];
    [refreshControl addTarget:self action:@selector(didPullToRefresh) forControlEvents:UIControlEventValueChanged];

    [self.scrollView addSubview:refreshControl];
 }

 - (void)didPullToRefresh
 {

 }
like image 57
Rafał Augustyniak Avatar answered Oct 09 '22 09:10

Rafał Augustyniak


As of iOS 6 there is a refreshControl property on UIScrollView (and hence it's subclasses, UITableView and UICollectionView).

Code from the Apple documentation: https://developer.apple.com/documentation/uikit/uirefreshcontrol#//apple_ref/occ/instm/UIRefreshControl

func configureRefreshControl () {
   // Add the refresh control to your UIScrollView object.
   myScrollingView.refreshControl = UIRefreshControl()
   myScrollingView.refreshControl?.addTarget(self, action:
                                      #selector(handleRefreshControl),
                                      for: .valueChanged)
}

@objc func handleRefreshControl() {
   // Update your content…

   // Dismiss the refresh control.
   DispatchQueue.main.async {
      self.myScrollingView.refreshControl?.endRefreshing()
   }
}
like image 20
Ric Santos Avatar answered Oct 09 '22 11:10

Ric Santos