想要下拉重新整理表格式資料,上拉載入新資料,網上有許多第三方的實作類別。
而如果僅僅需要實現下拉重新整理資料的話,那麼使用 UIRefreshControl 就足夠了,簡單有好用。
1,UIRefreshControl 的使用步驟:
(1)建立 UIRefreshControl,並設定文字,顏色等資訊。
(2)將 UIRefreshControl 添加到tableview視圖中。
(3)給 UIRefreshControl 添加方法,當值改變的時候調用,用於資料請求重新整理。
(4)請求資料確認完成之後,調用endRefreshing方法,關閉重新整理。
2,效果圖如下
代碼如下
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//新聞列表
@IBOutlet weak var newsTableView: UITableView!
//新聞數組集合
var dataArray:[HanggeArticle] = [HanggeArticle]()
//拉重新整理控制器
var refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
//添加重新整理
refreshControl.addTarget(self, action: "refreshData",
forControlEvents: UIControlEvents.ValueChanged)
refreshControl.attributedTitle = NSAttributedString(string: "下拉重新整理資料")
newsTableView.addSubview(refreshControl)
refreshData()
}
// 重新整理資料
func refreshData() {
//移除老資料
self.dataArray.removeAll()
//隨機添加5條新資料(時間是目前時間)
for _ in 0..<5 {
let atricle = HanggeArticle(title: "新聞標題\(Int(arc4random()%1000))",
createDate: NSDate())
self.dataArray.append(atricle)
}
self.newsTableView.reloadData()
self.refreshControl.endRefreshing()
}
// 返回記錄數
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count;
}
// 返回儲存格內容
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
reuseIdentifier: "myCell")
//設定儲存格標題
let atricle: HanggeArticle = dataArray[indexPath.row] as HanggeArticle
cell.textLabel?.text = atricle.title
//設定儲存格副標題
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let str = dateFormatter.stringFromDate(atricle.createDate)
cell.detailTextLabel?.text = str
return cell;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//新聞結構體
struct HanggeArticle {
var title:String
var createDate:NSDate
}