Search code examples
iosiphoneuiscrollviewxamarin.iosuirefreshcontrol

Can I use a UIRefreshControl in a UIScrollView?


I have about 5 UIScrollView's already in my app which all load multiple .xib files. We now want to use a UIRefreshControl. They are built to be used with UITableViewControllers (per UIRefreshControl class reference). I do not want to re-do how all 5 UIScrollView work. I have already tried to use the UIRefreshControl in my UIScrollView's, and it works as expected except for a few things.

  1. Just after the refresh image turns into the loader, the UIScrollView jumps down about 10 pixels, which only does not happen when I am very careful to drag the UIScrollview down very slowly.

  2. When I scroll down and initiate the reload, then let go of the UIScrollView, the UIScrollView stays where I let it go. After it is finished reloading, the UIScrollView jumps up to the top with no animation.

Here is my code:

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

-(void)handleRefresh:(UIRefreshControl *)refresh {
      // Reload my data
      [refresh endRefreshing];
}

Is there any way I can save a bunch of time and use a UIRefreshControl in a UIScrollView?

Thank You!!!


Solution

  • Since iOS 10 UIScrollView already has a refreshControl property. This refreshControl will appear when you create a UIRefereshControl and assign it to this property.

    There's no need to add UIRefereshControl as a subview anymore.

    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()
       }
    }
    

    A UIRefreshControl object is a standard control that you attach to any UIScrollView object

    Code and quote from https://developer.apple.com/documentation/uikit/uirefreshcontrol