菜鸟教程小白 发表于 2022-12-11 22:40:37

ios - 将数据从数组加载到 UITableView 单元格的问题


                                            <p><p>我对快速编程和尝试构建一个应用程序来接受订单并将它们中继到管理应用程序非常陌生。我的数据没有加载到我的 UITableView 中,我不知道为什么,据我所知,我已经按照书本完成了所有工作。我正在从我创建的节点服务器加载数据,并且在打印数组的内容时,所有项目都打印为键、对值。 UIimage 正在每个 tableView 单元格中加载,但标签没有加载,在设置标签并打印它们之后,标签的值仍然为零。 </p>

<p>我创建了一个名为 <code>PizzaListTableViewController</code> 的 TableView 类和一个名为 <code>PizzaTableViewCell</code> 的自定义 TableViewCell <code>class</code>。我在 Storyboard界面构建器中添加了一个 UIimage 和三个标签。</p>

<blockquote>
<p>Structure is: ViewController &gt; TableView &gt; TableViewCell &gt; Image, Labels</p>
</blockquote>

<p>我的主 VC 连接到它的 <code>ViewController.class</code>
我的 TableViewCell 连接到它的 TableViewCell.class
我有一个标识符并将其链接起来,如下面的代码所示
我连接了所有的网点。任何帮助将不胜感激!</p>

<p>我试图重写类,断开所有导出连接并重新连接它们,在设置标签的方法中分配值但没有任何运气。</p>

<pre><code>class PizzaListTableViewController: UITableViewController {
    var pizzas: = []

    override func viewDidLoad() {
      super.viewDidLoad()
      //title you will see on the app screen at the top of the table view
      navigationItem.title = &#34;Drink Selection&#34;

      //tableView.estimatedRowHeight = 134
      //tableView.rowHeight = UITableViewAutomaticDimension

      fetchInventory { pizzas in
            guard pizzas != nil else { return }
            self.pizzas = pizzas!
            //print(self.pizzas)
            self.tableView.reloadData()
            //print(self.pizzas)
      }


    }   //end of viewDidLoad

    private func fetchInventory(completion: @escaping (?) -&gt; Void) {
      Alamofire.request(&#34;http://127.0.0.1:4000/inventory&#34;, method: .get)
            .validate()
            .responseJSON { response in
                guard response.result.isSuccess else { return completion(nil) }
                guard let rawInventory = response.result.value as? [?] else { return completion(nil) }
                let inventory = rawInventory.compactMap { pizzaDict -&gt; Pizza? in
                  var data = pizzaDict!
                  data[&#34;image&#34;] = UIImage(named: pizzaDict![&#34;image&#34;] as! String)

                  //print(data)
                  //print(&#34;CHECK&#34;)
                  print(&#34;Printing all data: &#34;, Pizza(data: data))
                  //printing all inventory successful


                  return Pizza(data: data)
                }
                //self.tableView.reloadData()
                completion(inventory)
      }
    }

    @IBAction func ordersButtonPressed(_ sender: Any) {
      performSegue(withIdentifier: &#34;orders&#34;, sender: nil)
    }

    override func numberOfSections(in tableView: UITableView) -&gt; Int {
      return 1
    }

    //PRINTING ROWS 0 TWICE in console
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
      //print(&#34;ROWS&#34;, pizzas.count)
      return self.pizzas.count
    }


    //THIS IS WHERE THE CELL IDENTIFIER IS ??
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
      //print(&#34;IN CELLFORROWAT&#34;)

      tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: &#34;cell&#34;)

      let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: &#34;cell&#34;, for: indexPath) as! PizzaTableViewCell

      //cell.backgroundColor = Services.baseColor

      cell.name?.text = pizzas.name
      cell.imageView?.image = pizzas.image
      cell.amount?.text = &#34;$\(pizzas.amount)&#34;
      cell.miscellaneousText?.text = pizzas.description

      print(cell.name?.text! as Any)
      print(cell.imageView as Any)
      //print(&#34;END CELLFORROWAT&#34;)

      return cell
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat {
      return 100.0
    }//END OF

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      performSegue(withIdentifier: &#34;pizza&#34;, sender: self.pizzas as Pizza)
    }//END OF override func tableView

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if segue.identifier == &#34;pizza&#34; {
            guard let vc = segue.destination as? PizzaViewController else { return }
            vc.pizza = sender as? Pizza
      }
    }//END OF override preppare func

}
</code></pre>

<pre><code>class PizzaTableViewCell: UITableViewCell {

    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var pizzaImageView: UIImageView!
    @IBOutlet weak var amount: UILabel!

    @IBOutlet weak var miscellaneousText: UILabel!

    override func awakeFromNib() {
      super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
      super.setSelected(selected, animated: animated)

         //Configure the view for the selected state
    }

}
</code></pre>

<pre><code>struct Pizza {
    let id: String
    let name: String
    let description: String
    let amount: Float
    let image: UIImage

    init(data: ) {

      //print(&#34;CHECK:: pizza.swift&#34;)

      self.id = data[&#34;id&#34;] as! String
      self.name = data[&#34;name&#34;] as! String

//      self.amount = data[&#34;amount&#34;] as! Float
      self.amount = ((data[&#34;amount&#34;] as? NSNumber)?.floatValue)!

      self.description = data[&#34;description&#34;] as! String
      self.image = data[&#34;image&#34;] as! UIImage
    }

}
</code></pre>

<p>我还将数组的值打印到控制台,数据按预期打印,但 <code>cell.name?.text</code>、<code>cell.amount?.text</code> 的值, 和 <code>cell.miscellaneousText?.text</code> 打印 nil.</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>请尝试在您作为参数传递给 fetchInventory 的代码中的主线程中重新加载您的 tableview:</p>

<pre><code>DispatchQueue.main.async {
    self.tableView.reloadData()
}
</code></pre>

<p>因此,您的 fetchInventory 调用应变为:</p>

<pre><code>    fetchInventory { pizzas in
      guard pizzas != nil else { return }
      self.pizzas = pizzas!
      //print(self.pizzas)
      DispatchQueue.main.async {
            self.tableView.reloadData()
      }
      //print(self.pizzas)
    }
</code></pre>

<p>请避免从后台线程执行 UI 工作,因为它不正确/不安全。此外,您也可以尝试在该主线程 block 内设置 self?.pizzas。
请考虑艾伦关于双重电话的建议。 </p>

<ol>
<li><p>请从 tableView/cellForRow 中彻底删除寄存器。</p>

<pre><code>// tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: &#34;cell&#34;)
</code></pre> </li>
<li><p>代替:</p>

<pre><code>cell.imageView?.image = pizzas.image
</code></pre>

<p>放:</p>

<pre><code>cell.pizzaImageView?.image = pizzas.image
</code></pre> </li>
</ol>

<p>这是您的分店名称。</p>

<p>请检查我下面的测试是否有效 <a href="/image/cO4qE.png" rel="noreferrer noopener nofollow"><img src="/image/cO4qE.png" alt="enter image description here"/></a> :</p>

<pre><code>import UIKit
</code></pre>

<p>类 PizzaListTableViewController: UITableViewController {</p>

<pre><code>var pizzas: = []

override func viewDidLoad() {
    super.viewDidLoad()
    //title you will see on the app screen at the top of the table view
    navigationItem.title = &#34;Drink Selection&#34;

    //tableView.estimatedRowHeight = 134
    //tableView.rowHeight = UITableViewAutomaticDimension

    fetchInventory { pizzas in
      guard pizzas != nil else { return }
      self.pizzas = pizzas!
      print(self.pizzas)
      DispatchQueue.main.async {
            self.tableView.reloadData()
      }
      //print(self.pizzas)
    }
}   //end of viewDidLoad

private func fetchInventory(completion: @escaping (?) -&gt; Void) {
    let rawInventory0 = [
      [
            &#34;id&#34;: &#34;1&#34;,
            &#34;name&#34;: &#34;name1&#34;,
            &#34;amount&#34;: 1234,
            &#34;description&#34;: &#34;description1&#34;,
            &#34;image&#34;: &#34;image1&#34;
      ],
      [
            &#34;id&#34;: &#34;2&#34;,
            &#34;name&#34;: &#34;name2&#34;,
            &#34;amount&#34;: 1235,
            &#34;description&#34;: &#34;description2&#34;,
            &#34;image&#34;: &#34;image2&#34;
      ],
      [
            &#34;id&#34;: &#34;3&#34;,
            &#34;name&#34;: &#34;name3&#34;,
            &#34;amount&#34;: 1236,
            &#34;description&#34;: &#34;description3&#34;,
            &#34;image&#34;: &#34;image3&#34;
      ],
      [
            &#34;id&#34;: &#34;4&#34;,
            &#34;name&#34;: &#34;name4&#34;,
            &#34;amount&#34;: 1237,
            &#34;description&#34;: &#34;description4&#34;,
            &#34;image&#34;: &#34;image4&#34;
      ]
    ]as? [?]
    guard let rawInventory1 = rawInventory0 as? [?] else { return completion(nil) }
    let inventory = rawInventory1.compactMap { pizzaDict -&gt; Pizza? in
      var data = pizzaDict!
      data[&#34;image&#34;] = UIImage(named: pizzaDict![&#34;image&#34;] as! String)
      print(data)
      print(&#34;CHECK&#34;)
      print(&#34;Printing all data: &#34;, Pizza(data: data))
      //printing all inventory successful
      return Pizza(data: data)
    }
    //self.tableView.reloadData()
    completion(inventory)
}

// MARK: - Table view data source

@IBAction func ordersButtonPressed(_ sender: Any) {
    performSegue(withIdentifier: &#34;orders&#34;, sender: nil)
}

override func numberOfSections(in tableView: UITableView) -&gt; Int {
    return 1
}

//PRINTING ROWS 0 TWICE in console
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
    //print(&#34;ROWS&#34;, pizzas.count)
    return self.pizzas.count
}


//THIS IS WHERE THE CELL IDENTIFIER IS ??
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
    //print(&#34;IN CELLFORROWAT&#34;)

    // tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: &#34;cell&#34;)

    let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: &#34;cell&#34;, for: indexPath) as! PizzaTableViewCell

    //cell.backgroundColor = Services.baseColor

    cell.name?.text = pizzas.name
    cell.pizzaImageView?.image = pizzas.image
    cell.amount?.text = &#34;\(pizzas.amount)&#34;
    cell.miscellaneousText?.text = pizzas.description

    print(cell.name?.text! as Any)
    //print(cell.imageView as Any)
    //print(&#34;END CELLFORROWAT&#34;)

    return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat {
    return 100.0
}//END OF

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: &#34;pizza&#34;, sender: self.pizzas as Pizza)
}//END OF override func tableView

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == &#34;pizza&#34; {
      guard let vc = segue.destination as? PizzaViewController else { return }
      vc.pizza = sender as? Pizza
    }
}//END OF override preppare func
</code></pre>

<p>}</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 将数据从数组加载到 UITableView 单元格的问题,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/55525768/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/55525768/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 将数据从数组加载到 UITableView 单元格的问题