Swift tableView分页 [英] Swift tableView Pagination

查看:112
本文介绍了Swift tableView分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用json解析代码成功地工作tableview。但是可能还有1000个项目,因此在滚动底部时需要分页。我不知道我怎么能在下面做我的代码。对于objective-c有很多例子但是对于swift我没有找到工作的例子。我在等你的帮助。我想会帮助太多人。谢谢 !

  import UIKit 

class ViewController:UIViewController,UITableViewDataSource,UITableViewDelegate {

让kSuccessTitle =祝贺
让kErrorTitle =连接错误
让kNoticeTitle =通知
让kWarningTitle =警告
让kInfoTitle =Info
let kSubtitle =你刚刚显示了这个真棒弹出视图


@IBOutlet弱变量myTableView:UITableView!
@IBOutlet weak var myActivityIndi​​cator:UIActivityIndi​​catorView!

var privateList = [String]()

覆盖func viewDidLoad(){
super.viewDidLoad()
//之后进行任何其他设置通常从笔尖加载视图。

}

覆盖func viewWillAppear(动画:Bool){
super.viewWillAppear(动画)

loadItems()

}

覆盖func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
//处置可以重新创建的任何资源。
}


内部函数tableView(tableView:UITableView,numberOfRowsInSection section:Int) - > Int
{
返回privateList.count
}




内部函数tableView(tableView:UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell
{

让cell:myCell = tableView.dequeueReusableCellWithIdentifier(myCell)为! myCell

cell.titleLabel.text = privateList [indexPath.row]


return cell
}


func tableView(tableView:UITableView,commitEditingStyle editingStyle:UITableViewCellEditingStyle,forRowAtIndexPath indexPath:NSIndexPath){

if(editingStyle == UITableViewCellEditingStyle.Delete){

print(indexPath。行)


let alert = SCLAlertView()
alert.addButton(Hayır){}
alert.addButton(Evet){

self.myTableView.beginUpdates()

self.privateList.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath],withRowAnimation:UITableViewRowAnimation.Left)
print(Silindi)

self.myTableView.endUpdates()

self.loadItems()

}
alert .showSuccess (kSuccessTitle,subTitle:kSubtitle)

}


}





func tableView(tableView:UITableView,canEditRowAtIndexPath indexPath:NSIndexPath) - > Bool {
//您想要显示操作的单元格需要可编辑
返回true
}



覆盖func prepareForSegue(segue:UIStoryboardSegue,sender:AnyObject?){


if(segue.identifier ==Detail){

let destinationView = segue.destinationViewController如! DetailViewController

如果让indexPath = myTableView.indexPathForCell(发送者为!UITableViewCell){

destinationView.privateLista = privateList [indexPath.row]

}
}
}



内部函数tableView(tableView:UITableView,estimatedHeightForHeaderInSection section:Int) - > CGFloat
{
return 0.0
}


func loadItems()
{
loadItemsNow(privateList)

}

func loadItemsNow(listType:String){
myActivityIndi​​cator.startAnimating()
let listUrlString =http://bla.com/json2。 php?listType =+ listType +& t =+ NSUUID()。UUIDString
let myUrl = NSURL(string:listUrlString);
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod =GET;

let task = NSURLSession.sharedSession()。dataTaskWithRequest(request){
data,response,error in

if error!= nil {
print(error!.localizedDescription)
dispatch_async(dispatch_get_main_queue(),{
self.myActivityIndi​​cator.stopAnimating()
})

return
}


do {

让json =尝试NSJSONSerialization.JSONObjectWithData(data!,options:.MutableContainers)为? NSArray

如果让parseJSON = json {


self.privateList = parseJSON as! [String]

}

} catch {
print(error)

}

dispatch_async( dispatch_get_main_queue(),{
self.myActivityIndi​​cator.stopAnimating()
self.myTableView.reloadData()
})


}

task.resume()
}


}


解决方案

为此,您还需要进行服务器端更改。


  1. 服务器将在 API 中接受 fromIndex batchSize url作为查询参数。

      let listUrlString =http://bla.com/json2.php?listType=+ listType +& t =+ NSUUID()。UUIDString +& batchSize =+ batchSize +& fromIndex =+ fromIndex 


  2. 在服务器响应中,将有一个额外的密钥 totalItems 。这将用于识别是否收到所有项目。一个或多个项目 fromIndex batchSize 项目数。


在应用程序端


  1. 首先将使用 fromIndex = 0 batchSize = 20 调用loadItem()(例如在 viewDidLoad() viewWillAppear )。在第一次调用 loadItem()之前从 privateList 数组中删除所有项目


  2. 服务器返回前20个项目的数组, totalItems 服务器中的项目总数。


  3. privateList 数组中追加20项并重新加载 tableView


  4. tableView:cellForRowAtIndexPath 方法中检查单元格是否是最后一个单元格。并检查 totalItems (表单服务器)是否大于 privateList.count 。这意味着服务器中有更多项目要加载

     如果indexPath.row == privateList.count  -  1 {// last cell 
    if totalItems> privateList.count {//更多项目来获取
    loadItem()//在服务器调用
    }
    }
    之前,将`fromIndex`增加20 / pre>






问题: 哪里刷新?将滚动?



收到服务器响应后,在数组中追加新项目后刷新。 (步骤3)



当用户滚动时,滚动将触发每个单元格的 tableView:cellForRowAtIndexPath 。代码正在检查它是否是最后一个单元格并获取剩余项目。 (步骤4)



添加的示例项目:
https:// github。 com / rishi420 / TableViewPaging


I have success working tableview with json parsing codes.But may have 1000 more item so need pagination when scrolling bottom side. I dont know how can i do this my codes under below. For objective-c have a lot of example but for swift i didnt find working example. Im waiting your helps. I think will be help too many people. Thank you !

import UIKit

class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate {

    let kSuccessTitle = "Congratulations"
    let kErrorTitle = "Connection error"
    let kNoticeTitle = "Notice"
    let kWarningTitle = "Warning"
    let kInfoTitle = "Info"
    let kSubtitle = "You've just displayed this awesome Pop Up View"


    @IBOutlet weak var myTableView: UITableView!
    @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!

    var privateList = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        loadItems()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    internal func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return privateList.count
    }




    internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

       let cell:myCell = tableView.dequeueReusableCellWithIdentifier("myCell") as! myCell

        cell.titleLabel.text = privateList[indexPath.row]


        return cell
    }


    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        if (editingStyle == UITableViewCellEditingStyle.Delete){

         print(indexPath.row)


            let alert = SCLAlertView()
            alert.addButton("Hayır"){ }
            alert.addButton("Evet") {

                self.myTableView.beginUpdates()

                 self.privateList.removeAtIndex(indexPath.row)
                tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
                print("Silindi")

                self.myTableView.endUpdates()

                  self.loadItems()

            }
            alert.showSuccess(kSuccessTitle, subTitle: kSubtitle)

        }


    }





    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // the cells you would like the actions to appear needs to be editable
        return true
    }



    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {


        if(segue.identifier == "Detail") {

            let destinationView = segue.destinationViewController as! DetailViewController

            if let indexPath = myTableView.indexPathForCell(sender as! UITableViewCell) {

                destinationView.privateLista = privateList[indexPath.row]

            }
        }
    }



    internal func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat
    {
        return 0.0
    }


    func loadItems()
    {
     loadItemsNow("privateList")

    }

    func loadItemsNow(listType:String){
        myActivityIndicator.startAnimating()
        let listUrlString =  "http://bla.com/json2.php?listType=" + listType + "&t=" + NSUUID().UUIDString
        let myUrl = NSURL(string: listUrlString);
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "GET";

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil {
                print(error!.localizedDescription)
                dispatch_async(dispatch_get_main_queue(),{
                    self.myActivityIndicator.stopAnimating()
                })

                return
            }


            do {

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray

                if let parseJSON = json {


                        self.privateList = parseJSON as! [String]

                }

            } catch {
                print(error)

            }

            dispatch_async(dispatch_get_main_queue(),{
                self.myActivityIndicator.stopAnimating()
                self.myTableView.reloadData()
            })


        }

        task.resume()
    }


}

解决方案

For that you need to have server side change also.

  1. Server will accept fromIndex and batchSize in the API url as query param.

    let listUrlString =  "http://bla.com/json2.php?listType=" + listType + "&t=" + NSUUID().UUIDString + "&batchSize=" + batchSize + "&fromIndex=" + fromIndex
    

  2. In the server response, there will be an extra key totalItems. This will be used to identify all items are received or not. An array or items fromIndex to batchSize number of items.

In the app side

  1. First loadItem() will be called with fromIndex = 0 and batchSize = 20 (for example in viewDidLoad() or viewWillAppear). removeAll items from privateList array before calling loadItem() for the first time

  2. Server returns an array of first 20 items and totalItems total number of items in the server.

  3. Append the 20 items in privateList array and reload tableView

  4. In tableView:cellForRowAtIndexPath method check if the cell is the last cell. And check if totalItems (form server) is greater than privateList.count. That means there are more items in the server to load

    if indexPath.row == privateList.count - 1 { // last cell
        if totalItems > privateList.count { // more items to fetch
            loadItem() // increment `fromIndex` by 20 before server call
        }
    }
    


Question: where is refresh ? will be scrolling ?

Refresh after appending new items in the array when server response received. (step 3)

Scrolling will trigger tableView:cellForRowAtIndexPath for every cell when user scrolls. Code is checking if it is the last cell and fetch remaining items. (step 4)

Sample project added:
https://github.com/rishi420/TableViewPaging

这篇关于Swift tableView分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆