简体   繁体   中英

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

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?

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
 {

 }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM