UITableView上的iOS UIRefreshControl

In this tutorial, we’ll be implementing UIRefreshControl on the UITableView in our iOS Application.
You must have seen very often a spinning wheel when you pull the top of your screen in your iOS Applications. We’ll be implementing the same.

在本教程中,我们将在iOS应用程序的UITableView上实现UIRefreshControl。
在iOS应用程序中拉动屏幕顶部时,您一定经常看到旋转的轮子。 我们将实现相同的功能。

UIRefreshControl (UIRefreshControl)

A UIRefreshControl is a standard UI control element that is a part of the UI kit and is used to reload/refresh TableView, CollectionView or a ScrollView.

UIRefreshControl是UI工具包的一部分,是一个标准的UI控件元素,用于重新加载/刷新TableView,CollectionView或ScrollView。

Today, we’ll stick to UITableView only. Since iOS 10, UITableView consists of a refreshControl property which makes it easy to attach the UIRefreshControl element to the UITableView.

今天,我们将仅坚持使用UITableView。 从iOS 10开始,UITableView包含refreshControl属性,可轻松将UIRefreshControl元素附加到UITableView。

The UIRefreshControl consists of a progress indicator icon. We can optionally add a title message as well besides setting the background color of the UIRefreshControl.

UIRefreshControl包含进度指示器图标。 除了设置UIRefreshControl的背景颜色外,我们还可以选择添加标题消息。

UITableView is a subclass of UIScrollView hence the refreshControl property is already present in ScrollView.
UITableView是UIScrollView的子类,因此ScrollView中已经存在refreshControl属性。

To create a UIRefreshControl instance in Swift we do:

要在Swift中创建UIRefreshControl实例,请执行以下操作:

let myRefreshControl = UIRefreshControl()

We can then add this view to the UITableView as:

然后,我们可以将该视图添加到UITableView中,如下所示:

self.myTableView.refreshControl = myRefreshControl

//or

self.myTableView.addSubView(myRefreshControl)

We can set the title and font color on the UIRefreshControl in the following manner:

我们可以通过以下方式在UIRefreshControl上设置标题和字体颜色:

let myString = "Pull to refresh"
let myAttribute = [NSAttributedString.Key.foregroundColor: UIColor.white]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
refreshControl.attributedTitle = myAttrString

How to call a function when the UIRefreshControl is pulled?
Set the function inside the addTarget function invoked over the UIRefreshControl.

拉UIRefreshControl时如何调用函数?
在通过UIRefreshControl调用的addTarget函数内部设置函数。

refreshControl.addTarget(self, action: #selector(ViewController.handleRefresh), for: UIControl.Event.valueChanged)

Which function gets triggered when the pull to refresh gesture is performed?

执行拉动刷新手势时会触发哪个功能?

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)

Inside this function we can manually call a function depending on how fast the UITableView was pulled to refresh.
Sometimes the user doesn’t actually want to refresh. In these cases, they’re just slowly pulling the UITableView down and slowly leaving it to return to its original position.
In these cases, the velocity is less. We can decide to not trigger an action in such cases manually from this function.

在此函数内部,我们可以根据UITableView被拉动刷新的速度来手动调用函数。
有时用户实际上并不想刷新。 在这些情况下,他们只是在缓慢拉下UITableView并使其缓慢返回其原始位置。
在这些情况下,速度较小。 在这种情况下,我们可以决定通过此功能手动不触发操作。

Let’s create a new Single View Application in XCode.

让我们用XCode创建一个新的Single View Application。

In the Main.storyboard, add a UITableView to the View Controller, set the constraints. Set the delegates. Add the prototype cell and set the cell identifier as shown below:

在Main.storyboard中,将UITableView添加到视图控制器,设置约束。 设置代表。 添加原型单元并设置单元标识符,如下所示:

Connect the TableView to the ViewController.swift file.

将TableView连接到ViewController.swift文件。

Now add the following code inside the ViewController.swift file:

现在,在ViewController.swift文件中添加以下代码:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var myTableView: UITableView!
    var myArray = ["apple","windows","amazon"]
    
    lazy var refreshControl: UIRefreshControl = {
        let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(ViewController.handleRefresh), for: UIControl.Event.valueChanged)
        
        return refreshControl
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        myTableView.refreshControl = refreshControl
        //myTableView.addSubview(refreshControl)        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = myArray[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }
    
    @objc func handleRefresh()
    {
        let newElements = ["google","facebook","flipkart"]
        myArray.append(contentsOf: newElements)
        myArray.append(String(myArray.count))
        myTableView.reloadData()
        refreshControl.endRefreshing()
        
    }


}

UIRefreshControl is created using the lazy var property in Swift.
endRefreshing is called to close the UIRefreshControl.

UIRefreshControl是使用Swift中的lazy var属性创建的。
endRefreshing以关闭UIRefreshControl。

In the above code, we’ve set an Array of strings in the TableView.
Every time we refresh, we’ve added more elements in the UITableView.

在上面的代码中,我们在TableView中设置了一个字符串数组。
每次刷新时,我们都在UITableView中添加了更多元素。

The output of the application in action is given below:

实际应用程序的输出如下:

Let’s customise the UIRefreshControl now:

让我们现在自定义UIRefreshControl:

Change the viewDidLoad method to:

将viewDidLoad方法更改为:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        myTableView.refreshControl = refreshControl
        let myString = "Pull to refresh"
        let myAttribute = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 26)]
        let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
        refreshControl.attributedTitle = myAttrString
        refreshControl.tintColor = UIColor.white
        refreshControl.backgroundColor = UIColor.black
        
    }

We’ve added a tint color on the spinning wheel alongwith a background color on the complete UI control element.

我们在纺车上添加了色彩,并在完整的UI控件元素上添加了背景色。

The output of the application in action is given below:

实际应用程序的输出如下:

Remove the addTarget line of code from UIRefreshControl.
Add the following code inside the ViewController class:

从UIRefreshControl删除addTarget代码行。
在ViewController类中添加以下代码:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        print(velocity)
        
        if(velocity.y < -0.1)
        {
            handleRefresh()
        }
    }

We've noticed that the faster you pull the UIRefreshControl down, the higher the velocity would be in negative value. So we've added a condition that doesn't trigger the handleRefresh function until the value is in a negative value.

我们注意到,拉下UIRefreshControl的速度越快,速度的负值就越高。 因此,我们添加了一个条件,该条件在值变为负值之前不会触发handleRefresh函数。

The output of the application in action is given below:

实际应用程序的输出如下:

As it's visible, the values aren't getting updated since handleRefresh didn't trigger.
This is because we are not pulling it down and leaving the touch. We are still holding it while it goes back up which leads to a positive velocity.

可见,由于handleRefresh未触发,因此值未更新。
这是因为我们没有把它拉下来并保持接触。 当它返回并导致正速度时,我们仍将其保持住。

This brings an end to this tutorial. You can download the project from the link below:

本教程到此结束。 您可以从下面的链接下载项目:

翻译自: https://www.journaldev.com/22132/ios-uirefreshcontrol-uitableview

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值