Swift下拉刷新

/ / Swift下拉刷新

拉动刷新已超出移动应用程序的要求。目的是为用户提供将其下拉以刷新表或集合视图的内容的便利。在iOS应用程序中,将刷新刷新功能添加到tableview或collectionview已简化。

添加刷新控件

Apple为无涯教程提供了UIRefreshControl类,它简化了添加提要刷新的操作。无涯教程需要做的第一件事是实例化UIRefreshControl类。

let refreshControl = UIRefreshControl()

在这里,无涯教程需要将此刷新控件添加到无涯教程的表视图中。无涯教程可以将tableview的refreshControl属性分配给该实例。但是,无涯教程必须注意到,在iOS 10之前,没有诸如refreshControl之类的属性。无涯教程必须将其作为子视图添加到tableview中。

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/ios/ios-pull-to-refresh-functionality.html

来源:LearnFk无涯教程网

if #available(iOS 10.0, *) {
    tableView.refreshControl = refreshControl
} 
else {
    tableView.addSubview(refreshControl)
}

现在,无涯教程希望无涯教程的应用程序在表视图刷新上执行一些操作。无涯教程可以将其添加为UirefReshControl实例的目标。说法如下。

refreshControl.addTarget(self, action: #selector(function(_:)), for: .valueChanged)

现在,无涯教程都设置了在无涯教程的应用程序中进行刷新函数。考虑以下示例,无涯教程将刷新添加到TableView。

例子

在这个简单的示例中,无涯教程将创建一个tableView并使用数组填充它。在刷新时,无涯教程将为该数组附加一些值并用阵列重新加载tableView。

在这里,无涯教程创建了一个表格视图,并在其中添加了一个原型单元。无涯教程在单元格内添加了一个标签来显示消息。下拉时会刷新tableview内容。

Pull to refresh functionality

ViewController.swift

import UIKit


class ViewController: UIViewController {


    @IBOutlet weak var tableView: UITableView!
    
    let refreshControl = UIRefreshControl()
    var arr = Array<String>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       //Do any additional setup after loading the view.
        tableView.delegate = self
        tableView.dataSource = self
        arr = ["Value 1","Value 2","Value 3","Value 4"]
        tableView.refreshControl = refreshControl
        refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged)
    }


    @objc func refreshData(){
        for i in 7..<12{
            arr.append("Value "+i.description)
        }
        tableView.reloadData()
        refreshControl.endRefreshing()
    }
}
extension ViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
}


extension ViewController : UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
        cell.lbl.text = arr[indexPath.row]
        return cell
    }
}

祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)

精选教程推荐

👇 以下精选教程可能对您有帮助,拓展您的技术视野

程序员的AI开发第一课 -〔郑晔〕

结构思考力 · 透过结构看思考 -〔李忠秋〕

零基础GPT应用入门课 -〔林健(键盘)〕

程序员的测试课 -〔郑晔〕

OAuth 2.0实战课 -〔王新栋〕

消息队列高手课 -〔李玥〕

软件工程之美 -〔宝玉〕

Android开发高手课 -〔张绍文〕

从0开始学微服务 -〔胡忠想〕

📝 好记忆不如烂笔头,留下您的学习笔记吧!

暂无学习笔记,成为第一个分享的人吧!

您的笔记将帮助成千上万的学习者