ios - 检测tableView何时在底部滞后

标签 ios uitableview swift

我创建了一个连接到 api 的 tableView。我正在尝试实现加载更多功能,当您到达 tableView 的底部时,它会进行新的 api 调用。我已经创建了这个功能,但是当 api/json 文件中不再有对象时。当我到达底部时它似乎很滞后,这是怎么回事?

检测我何时位于屏幕底部并进行 api 调用

func scrollViewDidScroll(scrollView: UIScrollView!) {



    var height = scrollView.frame.size.height;
    var contentYoffset = scrollView.contentOffset.y;
    var distanceFromBottom = scrollView.contentSize.height - contentYoffset;

    if distanceFromBottom < height
    {
        if isApiCalling == false {
            getRecent("URL/recent.php?lastid=\(lastObjectIndex)&limit=\(numberOfRecordsPerAPICall)")
            self.tableVIew.reloadData()
        }
    }
}

GetRecent 函数。我什至创建了一个 isAPICalling 变量,以确保它不会多次运行 api。

func getRecent(url: NSString) {

    isApiCalling = true
    let recentUrl = NSURL(string: url as String)
    var recentRequest = NSURLRequest(URL: recentUrl!)
    var recentData = NSURLConnection.sendSynchronousRequest(recentRequest, returningResponse: nil, error: nil)

    let jsonArray = JSON(data: recentData!)
    for (key: String, subJson: JSON) in jsonArray {
        // Create an object and parse your JSON one by one to append it to your array
        var newNewsObject = News(id: subJson["id"].intValue, title: subJson["title"].stringValue, link: subJson["url"].stringValue, imageLink: subJson["image_url"].stringValue, summary: subJson["news_text"].stringValue, date: getDate(subJson["date"].stringValue))



        recentArray.append(newNewsObject)
    }

    lastObjectIndex = lastObjectIndex + numberOfRecordsPerAPICall
    isApiCalling = false


}

最佳答案

您可以将页脚添加到 tableview 部分,如果页脚被加载然后通过 API 调用调用下一组,(仅当 flag==-1 时加载页脚)

当请求下一次设置时,您可以设置标志(如 flag=1),该调用已经进行,因此如果用户再次向上和向下滚动,将不会发送请求(如果 标志==1)。

作为响应,将标志设置回正常(如flag=0),并检查响应,如果没有更多数据,则设置标志永远不加载页脚(如flag=-1).

附言确保第一次加载 View 时 flag 为 0。

这样可能会解决你的问题。

HTH,享受编码吧!

关于ios - 检测tableView何时在底部滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29696770/

相关文章:

ios - 在数组中查找对象?

iOS SWRevealViewController - 在 Controller 之间传递数据

ios - UIImage 在 int 数组中获取图像的像素

iphone - 检测 UITableView SECTION 上的触摸?

iOS 更改 UI 时,我应该从主线程调用什么?

swift - Firebase 性能未捕获的网络请求

swift - 在 macOS Mojave 中请求相机权限

objective-c - MPMoviePlayerController 播放直播流

ios - 正在使用 tableView :willSelectedRowAtIndexPath: correct way to pass variable?

ios - 使用 UITableView 和数组无限滚动