我正在使用swift构建一个RSS阅读器,需要实现重新加载功能。
以下是我如何努力做到这一点。
class FirstViewController: UIViewController,
UITableViewDelegate, UITableViewDataSource {
@IBOutlet var refresh: UIScreenEdgePanGestureRecognizer
@IBOutlet var newsCollect: UITableView
var activityIndicator:UIActivityIndicatorView? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.newsCollect.scrollEnabled = true
// Do any additional setup after loading the view, typically from a nib.
if nCollect.news.count <= 2{
self.collectNews()
}
else{
self.removeActivityIndicator()
}
view.addGestureRecognizer(refresh)
}
@IBAction func reload(sender: UIScreenEdgePanGestureRecognizer) {
nCollect.news = News[]()
return newsCollect.reloadData()
}
我得到:
财产的自我。刷新'未在super初始化。init调用
请帮助我理解手势识别器的行为。一个工作样例代码将是一个很大的帮助。
谢谢。
你可以使用tableView的子类:
import UIKit
protocol PullToRefreshTableViewDelegate : class {
func tableViewDidStartRefreshing(tableView: PullToRefreshTableView)
}
class PullToRefreshTableView: UITableView {
@IBOutlet weak var pullToRefreshDelegate: AnyObject?
private var refreshControl: UIRefreshControl!
private var isFirstLoad = true
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
if (isFirstLoad) {
addRefreshControl()
isFirstLoad = false
}
}
private func addRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: "refresh", forControlEvents: .ValueChanged)
self.addSubview(refreshControl)
}
@objc private func refresh() {
(pullToRefreshDelegate as? PullToRefreshTableViewDelegate)?.tableViewDidStartRefreshing(self)
}
func endRefreshing() {
refreshControl.endRefreshing()
}
}
1 -在接口构建器改变类你的tableView PullToRefreshTableView或创建一个PullToRefreshTableView编程
在你的视图控制器中实现PullToRefreshTableViewDelegate
当表视图开始刷新时,tableViewDidStartRefreshing(tableView: PullToRefreshTableView)将在视图控制器中被调用
4 -调用yourTableView.endRefreshing()来完成刷新
对于拉刷新,我正在使用
DGElasticPullToRefresh
https://github.com/gontovnik/DGElasticPullToRefresh
安装
豆荚的DGElasticPullToRefresh
import DGElasticPullToRefresh
然后把这个函数放到你的swift文件中,然后从你的
override func viewWillAppear(_ animated: Bool)
func Refresher() {
let loadingView = DGElasticPullToRefreshLoadingViewCircle()
loadingView.tintColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
self.table.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in
//Completion block you can perfrom your code here.
print("Stack Overflow")
self?.table.dg_stopLoading()
}, loadingView: loadingView)
self.table.dg_setPullToRefreshFillColor(UIColor(red: 255.0/255.0, green: 57.0/255.0, blue: 66.0/255.0, alpha: 1))
self.table.dg_setPullToRefreshBackgroundColor(self.table.backgroundColor!)
}
不要忘记在视图消失时删除引用
要删除拉刷新,请将此代码放入您的
重写func viewDidDisappear(_ animated: Bool)
override func viewDidDisappear(_ animated: Bool) {
table.dg_removePullToRefresh()
}
看起来就像
快乐编码:)