Swift iOS : 內置的下拉刷新

對TableView,下拉刷新新的數據是很方便的。iOS內置有一個下拉刷新控件UIRefreshControl,雖然不能作上拉刷新,可是由於使用簡單,倒也值得介紹。bash

以下代碼,使用TableView加載OS列表,每次下拉,都模擬刷新一條新的OS項目:app

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let page = Page()
        page.view.backgroundColor = .blue
        self.window!.rootViewController = page
        self.window?.makeKeyAndVisible()
        return true
    }
}
class Page: UIViewController {
    var a : Table!
    override func viewDidLoad() {
        super.viewDidLoad()
        a  = Table()
        a.frame = self.view.frame
        self.view.addSubview(a)
        refreshControl = UIRefreshControl()
        refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
        refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
        a.addSubview(refreshControl)
    }
    var refreshControl: UIRefreshControl!
    var index = 0
    let oses = ["1","2","3","4",]
    func refresh(sender:AnyObject) {
        if index < oses.count  {
            a.os.insert("os - " + oses[index], at: 0)
            a.reloadData()
            index += 1
        }
        refreshControl.endRefreshing()
    }
}
class Table : UITableView,UITableViewDataSource,UITableViewDelegate{
    var os = ["Windows","OS X","Linux"]
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame:frame,style:style)
        self.dataSource = self
        self.delegate = self
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    }
    func numberOfSections(in: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return os.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let arr = os
        let a = UITableViewCell(style: .default, reuseIdentifier: nil)
        a.textLabel?.text = String(describing:arr[indexPath.row])
        return a
    }
}複製代碼

其餘的內容,和正常的TableView加載數據相似。不一樣的就是,這裏建立了一個UIRefreshControl的實例,並添加一個.valueChanged的目標到函數refresh,這樣每次下拉,都會觸發一次此函數,在這個函數裏面,會對TableView的數據源作插入,並從新加載TableView。ide

執行起來,試試下拉,能夠看到效果。函數

相關文章
相關標籤/搜索