【问题标题】:tableView cell is not showing any content in the cell but it is printing content in consoletableView 单元格未显示单元格中的任何内容,但它正在控制台中打印内容
【发布时间】:2019-10-22 15:26:52
【问题描述】:

我创建了一个UITableView 并希望将我的结果从 api 显示到UITableView 中的单元格。有一个单元格类,其中包含标签的出口,但单元格中没有显示任何内容。结果显示在控制台中,但不在单元格标签中

我已尝试删除和添加新约束。 我还添加了一个按钮来重新加载 UITableView 的内容,但没有任何帮助。

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customCellTableViewCell
        var result: String!
        Alamofire.request(booksUrl, method: .get).responseJSON { (response) in

            if response.result.isSuccess{
                let bookJSON : JSON = JSON(response.result.value)
                let tempResult = bookJSON["items"][0]["volumeInfo"]["title"].stringValue
                result = tempResult
                print(tempResult)
            }
        }

        cell.bookNameLabel?.text = result
       return cell
    }

【问题讨论】:

    标签: ios swift xcode api uitableview


    【解决方案1】:

    请注意,Alamofire(和大多数网络请求)是异步的,这意味着在分派请求的那一刻,结果是未知的。

    但是tableview的datasource函数是同步方法,必须立即返回cell。

    最终的结果是,当请求cell时,结果未知,将cell返回给tableview进行显示。一段时间后,收到网络请求的结果,打印在屏幕上,但单元格从未更新。

    显示您的信息所需的最少更改量是:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customCellTableViewCell
            Alamofire.request(booksUrl, method: .get).responseJSON { (response) in
    
                if response.result.isSuccess{
                    let bookJSON : JSON = JSON(response.result.value)
                    let tempResult = bookJSON["items"][0]["volumeInfo"]["title"].stringValue
                    print(tempResult)
                    cell.bookNameLabel?.text = tempResult
                }
            }
           return cell
        }
    

    更新后的代码所做的是使用 Alamofire 回调中的“cell”变量实例来更新单元格标签。请注意,这不是应该的方式,就好像您开始拥有许多单元格,其中许多单元格可能会被重复使用,最终您的数据会到处出现并变得非常混乱。

    您可能希望在该函数之外获取网络请求,并在自定义 UITableViewCell 中执行网络请求,如果单元被重用或从视图控制器的 viewDidLoad 函数调度,请确保取消网络请求完整/部分 tableView.reloadData()。

    鉴于您的 API 调用似乎检索书籍列表并且每个单元格都显示一个书名,我建议执行一次请求,将所有书籍结果存储到一个数组中,然后返回等于您的数组中的书籍数量。

    另一方面,您应该努力将在任何功能中执行的不同任务的数量保持在最低限度。所以应该返回一个单元格的函数应该返回一个单元格,就是这样......不执行网络请求。

    推荐的代码结构会更接近这个:

       var books: JSON?
    
       override func viewDidLoad() {
           super.viewDidLoad()
           retrieveListOfBooks()
       }
    
       func retrieveListOfBooks() {
            Alamofire.request(booksUrl, method: .get).responseJSON { (response) in
                DispatchQueue.main.async {
                    if response.result.isSuccess{
                        self.books = JSON(response.result.value)
                        self.tableView.reloadData()
                    }
                }
            }
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return books?["items"].count ?? 0
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customCellTableViewCell
            if indexPath.row < (books?["items"].count ?? 0) {
                 let book = books!["items"][indexPath.row]
                 let bookTitle = book["volumeInfo"]["title"].stringValue
                 cell.bookNameLabel?.text = bookTitle
            }
           return cell
        }
    

    警告:我还没有测试过上面的代码,您可能还应该使用 Codable 来表示您的图书数据模型。

    【讨论】:

    • 非常感谢@ekscrypto,它起作用了,我还将更改 cellForRowAt 函数的功能。再次感谢。
    • @JaiNijhawan 我添加了更多代码来指导您如何更接近您的预期。我很高兴我提供的解决方案很有帮助。请标记已回答的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多