在UITableView的底部加载更多

对于我的应用程序,我使用“加载更多底部”属性,如下所示。 它实际上工作得很好; 唯一的问题是当用户到达按钮时,当加载更多function正在工作时,对于用户来说它看起来像应用程序冻结一段时间,因为没有像UIRefreshcontrol中的动画视图。 如何在加载新数据之前显示动画。 我发现一些UIBottomrefreshcontrol属性作为单独的库,但它们都在Objective-c中。

 override func viewDidLoad() { super.viewDidLoad() refreshResults() } func refreshResults() { refreshPage = 40 // here the query starts } func refreshResults2() { // here the query starts to add new 40 rows of data to arrays } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == refreshPage-1 { refreshPage = refreshPage + 40 refreshResults2() } } 

UIActivityIndicatorView (即微调器)添加到UITableViewController。 将sockets连接到代码:

 @IBOutlet weak var spinner: UIActivityIndicatorView! 

UITableViewController添加一个属性,以跟踪您当前正在加载更多数据,这样您就不会尝试两次:

 var loadingData = false 

启动微调器动画,然后调用refreshResults2()

 func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if !loadingData && indexPath.row == refreshPage - 1 { spinner.startAnimating() loadingData = true refreshResults2() } } 

refreshResults2()在后台线程上运行。 这将使您的桌子仍然可以自由移动。 动画微调器将告诉用户更多数据即将到来。 查询返回后,更新主线程上的表数据。

 func refreshResults2() { dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { // this runs on the background queue // here the query starts to add new 40 rows of data to arrays dispatch_async(dispatch_get_main_queue()) { // this runs on the main queue self.refreshPage += 40 self.tableView.reloadData() self.spinner.stopAnimating() self.loadingData = false } } } 
  • Swift 3,Xcode 8
  •  func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let lastElement = dataSource.count - 1 if !loadingData && indexPath.row == lastElement { spinner.startAnimating() loadingData = true loadMoreData() } } 

    根据swift 3中的@vacawama异步调用: –

     func loadMoreData() { DispatchQueue.global(qos: .background).async { // this runs on the background queue // here the query starts to add new 10 rows of data to arrays DispatchQueue.main.async { // this runs on the main queue self.spinner.stopAnimating() self.loadingData = false } } }