【问题标题】:Add more data when tableview reached end当 tableview 到达结束时添加更多数据
【发布时间】:2018-04-16 09:17:36
【问题描述】:

我正在使用Alamofire 从服务器获取一些数据,如下所示:

func getNewestFeed(order:String , page:Int)  {
        Alamofire.request("https://blahblah.com/api/front/\(page)/\(order)", method: .post, parameters: ["foo":"bar"], encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: { respone in

            if respone.response?.statusCode == 200 {

                let result = respone.result.value as! [String:Any]
                self.newestArray = result["records"] as! [Any]
                self.tableView.reloadData()


            } else {
                //Show error
                let alertController = UIAlertController(title: "Error", message: "", preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
                alertController.addAction(cancelAction)
                OperationQueue.main.addOperation { self.present(alertController, animated: true, completion: nil) }
            }

        })
    }

默认服务器给我第 1 页,现在我也需要添加更多数据self.newestArray 以加载更多内容。所以这里是代码:

  func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        let lastElement = newestArray.count - 1

        if indexPath.row == lastElement {

            //add more data 
        }
    }

现在我正在尝试将 result 添加到 self.newestArray ,如下所示:

let result = respone.result.value as! [String:Any]  
                self.newestArray.append(result["records"] as! [Any])
                self.tableView.reloadData()

但因此错误而崩溃:

无法将 'Swift.Array' (0x109c3c828) 类型的值转换为 'Swift.Dictionary' (0x109c3c798)。

我应该如何向self.newestArray 添加更多数组并在表格视图中再次显示?

【问题讨论】:

  • append的参数类型是单个对象。还有一种方法采用 array 对象。请阅读documentation

标签: ios arrays swift uitableview dictionary


【解决方案1】:

append(_:) 用于在数组末尾添加一个单个元素。 有append(contentsOf:)如果要添加项目集合:

self.newestArray.append(contentsOf: result["records"] as! [Any])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多