我在ViewController中使用func tableView(_ tableView:UITableView,willDisplay cell:UITableViewCell,forRowAt indexPath:IndexPath)方法对API请求的结果进行分页。一切正常,当我向下滚动并到达最后一个单元格时,将加载下一页,但是我的问题是,当我使用refreshControl刷新表格视图时,我的意思是,当我滚动到顶部并调用refreshControl时,我只需要加载第一页,但之前已加载的所有页均已收费,因为willDisplay已触发。
class UsersViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate, floatMenuDelegate, UISearchBarDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshTableMain), for: .valueChanged)
usersTable.refreshControl = refreshControl
}
@objc func refreshTableMain(refreshControl: UIRefreshControl) {
self.page = 1
self.cUsers.removeAll(keepingCapacity: false)
self.cSearchUsers.removeAll(keepingCapacity: false)
self.getUsers(self.page, searchText: self.usersSearchBar.text!, isSearching: false)
refreshControl.endRefreshing()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastSectionIndex = tableView.numberOfSections - 1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1
if indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex {
if page < totalPages{
page = page + 1
getUsers(page, searchText: searchTextField.text!, isSearching: false)
}
}
}
func getUsers(_ page: Int, searchText: String, isSearching: Bool) {
//get Users of each page
// reloadData is called here
}
}