【问题标题】:Json request retrieving results but only displaying the first resultJson 请求检索结果但只显示第一个结果
【发布时间】:2021-02-01 12:52:48
【问题描述】:

我有一个表格视图,它从 api 请求中获取数据,从该请求中它只显示第一个结果。

//MARK:-- Computed vars
var listOfLodges = [LodgeDetail](){
    didSet{
        DispatchQueue.main.async {
            self.tableView.reloadData()
            self.navigationItem.title = "\(self.listOfLodges.count) lodges found"
            print("\(self.listOfLodges.count) lodges found") // returns 11 lodges
            print(" ")
        }
    }
}

这里显示11个返回结果,所有数据都不一样。

//MARK: -- ViewDidLoad
        override func viewDidLoad() {
            super.viewDidLoad()
            loadData()
        }

//MARK:-- Setting up Table view
    @objc func setDelegate(){
        let landing = LandingViewController()
        landing.delegate = self
    }
 
    override func numberOfSections(in tableView: UITableView) -> Int {
        return listOfLodges.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

这可能是我的错误所在,我不确定可能出了什么问题?

// possible errors here
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for:indexPath)
        let lodge = listOfLodges[indexPath.row]
        let rating: String = String(lodge.rating!)//careful force unwrapping 

        print(rating) // prints the same 4.2
        print(lodge.name) //prints the same name
       
        return cell
    }
}
//MARK:-- Functions called on did load
extension ListViewController{
    func loadData(){
        let lodgeRequest = LodgeRequest(lat:passedLat, long:passedLong)
        lodgeRequest.getLodges{[weak self] result in
                    switch result{
                    case.failure(let error):
                        print(error)
                    case.success(let lodges):
                        self?.listOfLodges = lodges
                    }
            }
    }
}

【问题讨论】:

    标签: ios json swift uitableview


    【解决方案1】:

    改变

    let lodge = listOfLodges[indexPath.row]
    

    let lodge = listOfLodges[indexPath.section]
    

    由于每个部分只有一行,所以 indexPath.row 始终为 0,因此所有部分都显示第一项

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-12
      • 2021-11-01
      • 2017-01-19
      • 2012-06-23
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多