我可以为Swift中的UIViewController创建一个下拉刷新,而不是UITableViewController吗?

8

我有一个简单的应用程序,不需要使用UITableViewController来构建。是否有可能为简单的UIViewController创建“下拉刷新”功能?


1
是的,但你必须自己编写代码或者找到第三方库来帮助你。 - matt
2个回答

15

是的,有。事实上,要使用UIRefreshControl只需要满足一个条件 - 你可以将UIRefreshControl放在UIScrollView或其子类中(例如UITableViewUICollectionView)。

Swift示例代码:

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

    scrollView.addSubview(refreshControl)
}

func didPullToRefresh() {

}

Objective-c中的示例代码:

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

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

    [self.scrollView addSubview:refreshControl];
 }

 - (void)didPullToRefresh
 {

 }

1
在UIViewController中,你从哪里获取scrollView? - melaka
您需要创建一个,并将其添加为子视图。 - Ric Santos

6
自iOS 6以来,UIScrollView(和其子类,UITableViewUICollectionView)上有一个refreshControl属性。

来自Apple文档的代码: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()
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接