iOS 使用MJRefresh增加UITableView的上拉刷新,加载更多数据

iOS 使用MJRefresh增加UITableView的上拉刷新,加载更多数据

UITableView经常会加载很多很多数据,这样子我们就得做个类似分页的效果。MJRefresh能够很方便的让我们去实现这个效果。首先使用pod集成MJRefresh模块。

1
pod 'MJRefresh'

集成好后,直接贴代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import Foundation
import IBAnimatable
import MJRefresh
class TradeInfoViewController: AppViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
private var totalNumber = 12
private let sectionNumber = 5
private let sectionSpace: CGFloat = 40
var data = [1, 2]
override func viewDidLoad() {
super.viewDidLoad()
self.setNavigationTitle(Text_TradeInfo)
self.setNavigationBarColor(BlueColor)
self.addBackItemBtn()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.tableFooterView = UIView()
self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
self.tableView.mj_footer.backgroundColor = LightGrayColor
self.tableView.mj_footer.height = 44
}
/**
上拉刷新,加载更多数据
*/
func loadMoreData() {
DDLogError("--------------------loadMoreData")
// TODO::
let test_number = 7
if data.count >= test_number {
self.tableView.mj_footer.endRefreshingWithNoMoreData()
return
}
self.tableView.mj_footer.endRefreshing()
data.append(3)
data.append(4)
data.append(5)
self.tableView.reloadData()
}
// MARK: tableView delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = NSBundle.mainBundle().loadNibNamed("TradeInfoTableViewCell", owner: self, options: nil).last as! TradeInfoTableViewCell
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "2016年8月"
}
// 设置头部间距
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return sectionSpace
}
}

其他地方都不谈,这个是project里截取出来的一段testcase,虽然看起来多,但重要的都在self.tableView.mj_footer的初始化 and loadMoreData这个函数。大家自行参照撸码~MJRefresh很多人吐槽,但我觉得还不错~暂时还没进大坑~~~