滚动到底部时,UITableView加载更多

osa*_*kki 34 xcode uitableview swift

我想在用户滚动到表格底部时加载更多数据并创建其他单元格.我正在使用JSON数据和MySql.

func dataJsonFromURL(url:String)->NSArray
{
    if let data = NSData(contentsOfURL: NSURL(string: url)!) {
        return ((try! NSJSONSerialization.JSONObjectWithData(data, options: [])) as! NSArray)
    }
    else{
        return data
    }
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCellWithIdentifier("NCell", forIndexPath: indexPath) as! TableViewCell22

    cell.backgroundColor = UIColor .clearColor()

    let mindata = (data[indexPath.row] as! NSDictionary)
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*nVu 54

你必须使用这种方法

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
            let lastElement = dataSource.count - 1
            if indexPath.row == lastElement {
                // handle your logic here to get more items, add it to dataSource and reload tableview
                }    
        }
Run Code Online (Sandbox Code Playgroud)


Abd*_*rim 18

Xcode 8,Swift 3

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let lastElement = dataSource.count - 1
    if !loadingData && indexPath.row == lastElement {
        indicator.startAnimating()
        loadingData = true
        loadMoreData()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @AnupGupta dataSource只是你的数据数组,表视图得到它的值 (2认同)

Muh*_*med 6

我使用了这种方法,它对我有用

 func scrollViewDidScroll(scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height

    if offsetY > contentHeight - scrollView.frame.size.height {


        loadMoreDataFromServer()
        self.tableView.reloadData()
    }
}
Run Code Online (Sandbox Code Playgroud)


Hit*_*nki -9

使用这个库。 https://github.com/samvermette/SVPullToRefresh

这将完全满足您的要求。每次调用新的网络服务时,您只需要更改页码或时间戳即可。