上一次我們實現(xiàn)了緩存圖片加載,這一次我們在上次的基礎(chǔ)上加上下拉刷新,上拉加載。
申明var data:NSArray = NSArray()
,作為獲取數(shù)據(jù)的儲存,網(wǎng)絡(luò)數(shù)據(jù)獲取到后都放入data.下面創(chuàng)建下拉刷新和上拉加載婴氮。
var refreshing: Bool = false {
didSet {
if (self.refreshing) {
self.refreshControl?.beginRefreshing()
self.refreshControl?.attributedTitle = NSAttributedString(string: "Loading...")
println("Loading...")
}
else {
self.refreshControl?.endRefreshing()
self.refreshControl?.attributedTitle = NSAttributedString(string: "Pull to Refresh")
println("Loaded & set:Pull to Refresh")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
//添加下拉刷新
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: "onPullToFresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refreshControl!)
//上拉刷新
self.setupInfiniteScrollingView()
}
//下拉獲取數(shù)據(jù)
func onPullToFresh() {
fetchDataFromServer()
}
//上拉刷新
private func setupInfiniteScrollingView() {
self.infiniteScrollingView = UIView(frame: CGRectMake(0, self.tableView.contentSize.height, self.tableView.bounds.size.width, 60))
self.infiniteScrollingView!.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.infiniteScrollingView!.backgroundColor = UIColor.whiteColor()
var activityViewIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
activityViewIndicator.color = UIColor.darkGrayColor()
activityViewIndicator.frame = CGRectMake(self.infiniteScrollingView!.frame.size.width/2-activityViewIndicator.frame.width/2, self.infiniteScrollingView!.frame.size.height/2-activityViewIndicator.frame.height/2, activityViewIndicator.frame.width, activityViewIndicator.frame.height)
activityViewIndicator.startAnimating()
self.infiniteScrollingView!.addSubview(activityViewIndicator)
}
實現(xiàn)上拉加載的原理:
1.cellForRowAtIndexPath 中判斷下拉位置,執(zhí)行加載操作
2.第一次申請的數(shù)據(jù)(數(shù)組)放入data
3.第二次以后申請的數(shù)據(jù)使用arrayByAddingObjectsFromArray
往data填充盾致,更新tableView
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
//當(dāng)下拉到底部主经,執(zhí)行l(wèi)oadMore()
if (loadMoreEnabled && indexPath.row == self.data.count-1) {
self.tableView.tableFooterView = self.infiniteScrollingView
loadMore()
}
return cell
}
func loadMore(){
println("loadMore")
self.data = self.data.arrayByAddingObjectsFromArray(self.newData as! [String])
self.tableView.reloadData()
}