1. ホーム
  2. ios

Swift tableView のページ処理

2023-10-23 23:12:36

質問

私はjsonの解析コードで成功した作業テーブルビューを持っている。しかし、1000以上のアイテムを持っているかもしれないので、下側をスクロールするときにページネーションが必要です。私はどのように私は以下の私のコードをこれを行うことができますわからない。客観的なCのために多くの例を持っていますが、Swiftのために私は作業例を見つけられませんでした。私はあなたの助けを待っています。私はあまりにも多くの人々の助けになると思います。ありがとうございます!

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


}

どのように解決するのですか?

サーバー側を変更する必要があります。

  1. サーバーは fromIndexbatchSize の中に API をクエリパラメータとして指定します。

    let listUrlString =  "http://bla.com/json2.php?listType=" + listType + "&t=" + NSUUID().UUIDString + "&batchSize=" + batchSize + "&fromIndex=" + fromIndex
    
    
  2. サーバーのレスポンスに、余分なキーである totalItems . これは、すべてのアイテムが受信されたかどうかを識別するために使用されます。配列やアイテム fromIndex から batchSize の数を指定します。

アプリ側では

  1. 最初に loadItem() が呼び出され fromIndex = 0batchSize = 20 (は、(例えば viewDidLoad() または viewWillAppear からすべての項目を削除します。 privateList を呼び出す前に loadItem() を初めて呼び出す前に

  2. サーバーは最初の20個のアイテムの配列を返し totalItems の合計数を返します。

  3. の20項目を追加する。 privateList 配列に追加し、リロードして tableView

  4. tableView:cellForRowAtIndexPath メソッドは、そのセルが最後のセルであるかどうかをチェックします。そして totalItems (フォームサーバ) が privateList.count . これは、サーバーに読み込むべき項目がより多くあることを意味します。

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

質問です。 where is refresh ? will be scrolling ?

サーバーからの応答を受信したら、新しい項目を配列に追加した後、リフレッシュします。(ステップ3)

スクロールすると tableView:cellForRowAtIndexPath をトリガーします。コードは、それが最後のセルであるかどうかをチェックし、残りのアイテムをフェッチします。(ステップ 4)

サンプルプロジェクトを追加しました。

https://github.com/rishi420/TableViewPaging