2016-01-04 77 views
20

我想在用戶滾動到表格底部時加載更多數據並創建其他單元格。我正在使用JSON數據和MySql。當滾動到底部時,UITableView加載更多

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) 
} 

回答

-5

使用此庫。 https://github.com/samvermette/SVPullToRefresh

這將充分滿足你的要求。 您只需要在每次調用新的Web服務時更改頁碼或時間戳。

+0

我要爲迅速 –

+0

你可以使用Mix and Match,按照這篇文章https://developer.apple.com/librar Y/IOS /文檔/雨燕/概念/ BuildingCocoaApps/MixandMatch.html –

+0

或者如果你正在使用的CocoaPods,你可以直接使用,而不混搭通過只需要導入您viewcontroller.swift文件的頂部聲明。 –

1

它調用分頁到tableview。 分頁用於以有效的方式在桌面上顯示大量數據。 Here's你可以得到很好的教程目標c 並在此Question迅速的樣子。

而且你可以從Here下載迅速例子。

+0

我試過但不工作在我的代碼看到任何人都可以幫我修改它 –

+0

我需要一步一步;( –

1

你需要一個非常方便的委託方法:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell , forRowAtIndexPath indexPath: NSIndexPath) { 

} 

這種方法可以讓你的當前顯示的行。使用它提供的indexPath來確定何時接近表格的底部。然後獲取更多JSON並重新加載表格。

38

,你必須使用此方法

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 
       }  
     } 
+0

我真的很喜歡你的想法,它爲我工作,但是當我的最後一個產品查詢來了,它的正式最後一個,你的代碼仍然試圖帶來數據和表視圖閃爍任何想法如何停止它時,它帶來了最後一項? –

+1

@KwnstantinosNatsios很簡單,只需要添加另一個標誌就知道它可以裝載更多與否,如果仍然可以裝載更多=>做我的邏輯,如果不是=>忽略它 –

+0

這個標誌可能是項目的總數,但我認爲它以後:。d –

3

我用這個方法,它爲我

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() 
    } 
} 
+0

Assalamaleikum親愛的。爲什麼這段代碼在iPhone 5s中不起作用:scrollView.contentOffset.y == scrollView.contentSize.height - scrollView.frame.size.height? – Zhanserik

10

的作品Xcode中8,斯威夫特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() 
    } 
} 
+0

swift不讓我運行應用程序,因爲loadData loadMoreData它顯示錯誤「使用未解析的標識符」 –

+0

@Saeed Rahmatolahi檢查單元格標識符在UITableview中正確分配和使用 –

+0

您是否可以編輯此代碼請?我有我的tableview單元格中的一些文本,他們將通過json –

相關問題