我创建了一个连接到 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/