其实之前做OC的时候一直以为上拉刷新和下拉加载都是用运行时的原理去做的,可是今天看到案例的时候,发现有一个UIRefreshControl是专门做这个的,下面我们看看这个简单的下拉刷新具体是怎么做的吧
各项元素初始化#
let cellIdentifer = "NewCellIdentifier"
let favoriteEmoji = ["🤗🤗🤗🤗🤗", "", ""]
let newFavoriteEmoji = ["", "", "", "🤗🤗🤗🤗🤗", "", "" ]
var emojiData = [String]()
var tableViewController = UITableViewController(style: .plain)
var refreshControl = UIRefreshControl()
var navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 375, height: 64))
ViewDidLoad方法对视图进行调整#
override func viewDidLoad() {
super.viewDidLoad()
emojiData = favoriteEmoji
let emojiTableView = tableViewController.tableView
emojiTableView?.backgroundColor = UIColor(red:0.092, green:0.096, blue:0.116, alpha:1)
emojiTableView?.dataSource = self
emojiTableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifer)
tableViewController.refreshControl = self.refreshControl
self.refreshControl.addTarget(self, action: #selector(didRoadEmoji), for: .valueChanged)
self.refreshControl.backgroundColor = UIColor(red:0.113, green:0.113, blue:0.145, alpha:1)
let attributes = [NSForegroundColorAttributeName: UIColor.white]
self.refreshControl.attributedTitle = NSAttributedString(string: "Last updated on \(NSDate())", attributes: attributes)
self.refreshControl.tintColor = UIColor.white
self.title = "emoji"
self.navBar.barStyle = UIBarStyle.blackTranslucent
emojiTableView?.rowHeight = UITableViewAutomaticDimension
emojiTableView?.estimatedRowHeight = 60.0
emojiTableView?.tableFooterView = UIView(frame:.zero)
emojiTableView?.separatorStyle = UITableViewCellSeparatorStyle.none
self.view.addSubview(emojiTableView!)
self.view.addSubview(navBar)
}
func didRoadEmoji() {
self.emojiData = newFavoriteEmoji
self.tableViewController.tableView.reloadData()
self.refreshControl.endRefreshing()
}
TableView数据代理#
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return emojiData.count
}
private func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifer)! as UITableViewCell
cell.textLabel!.text = self.emojiData[indexPath.row]
cell.textLabel!.textAlignment = NSTextAlignment.center
cell.textLabel!.font = UIFont.systemFont(ofSize: 50)
cell.backgroundColor = UIColor.clear
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
基本的代码就是这样,有机会会对此做相应的改造,争取能封装成一个开源类库,本例代码请戳使用UIRefreshControl实现下拉刷新