【问题标题】:How to reload a tableView once a value has been appended to an array in swift 4.0在swift 4.0中将值附加到数组后如何重新加载tableView
【发布时间】:2020-10-26 13:38:29
【问题描述】:

将值附加到数组后,我在重新加载 tableView 时遇到问题。

这是我的代码

//
//  HomeViewController.swift
//  um
//
//  Created by Arnav on 17/09/18.
//  Copyright © 2018 Arnav. All rights reserved.
//

import UIKit
import Firebase
import FirebaseDatabase
import FirebaseAuth


class HomeTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var questions = [Question]()

    override  func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
//       var postQuestion = Question(questionName: "Hi", created_by: "Bye")
//       print(postQuestion.name)
//       print(postQuestion.created)

        loadQuestions()

    }

    var list = ["milk", "bread"]

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return list.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
        cell.textLabel?.text = list[indexPath.row]

        return cell
    }


    func loadQuestions() {
        Database.database().reference().child("questionPosts").queryOrderedByKey().observe(.childAdded) { (snapshot) in
            if let dict = snapshot.value as? NSDictionary {
                //var questionName = dict["name"] as! String
                //var created_by = dict["email"] as! String
                let questionTitle = dict["name"] as? String ?? ""
                let created_by = dict["email"] as? String ?? ""

                self.list.append(questionTitle)
            }
        }
    }

此代码只是向列表数组添加了一个新值,并且表格视图显示了列表数组中的内容,但是当我将新内容添加到列表数组并在模拟器上运行时,新值不会

【问题讨论】:

标签: ios uitableview firebase-realtime-database swift4


【解决方案1】:

您可以使用属性观察者didSet

var questions = [Question]() {
    didSet {
        Dispatch.main.async {
            self.tableView.reloadData()
        }
    }
}

欲了解更多信息click here

【讨论】:

    【解决方案2】:

    将新元素添加到list 后,在tableView 上调用insertRowAtIndexPaths:withRowAnimation,如下所示:

    self.list.append(questionTitle)
    let indexPath = IndexPath(row:self.list.count - 1, section:0)
    tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation:.default)
    

    【讨论】:

      【解决方案3】:

      你需要为你的 tableview 创建一个 outlet,一旦你的数据被加载,你就可以调用

      tableview.reloadData()
      

      或者,您可以在数组的didSet 上单元格上述函数,如下所示:

      var questions = [Question]() {
          didSet {
              // because we perform this operation on the main thread, it is safe
              DispatchQueue.main.async {
                  self?.tableView.reloadData()
              }
          }
      

      didSet 将在您每次更改问题数组中的某些内容时被调用

      【讨论】:

      • 如果网络调用会将 1000 项附加到数组中怎么办。这个重载函数会在这个 didSet 中调用 1000 个项目吗?如果是,那么另一种方法是什么?
      【解决方案4】:
      import UIKit
      import Firebase
      import FirebaseDatabase
      import FirebaseAuth
      
      
      
      class HomeTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
      
      
      
          var questions = [Question]()
      
          override  func viewDidLoad() {
              super.viewDidLoad()
      
              // Do any additional setup after loading the view.
      //       var postQuestion = Question(questionName: "Hi", created_by: "Bye")
      //       print(postQuestion.name)
      //       print(postQuestion.created)
      
              loadQuestions()
              yourtableView.reloadData()
      
          }
      
      
      
      
      
      
          var list = ["milk", "bread"]
      
      
      
      
          func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      
      
              return list.count
      
          }
      
          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
              cell.textLabel?.text = list[indexPath.row]
      
              return cell
          }
      
      
          func loadQuestions() {
              Database.database().reference().child("questionPosts").queryOrderedByKey().observe(.childAdded) { (snapshot) in
                  if let dict = snapshot.value as? NSDictionary {
                      //var questionName = dict["name"] as! String
                      //var created_by = dict["email"] as! String
                      let questionTitle = dict["name"] as? String ?? ""
                      let created_by = dict["email"] as? String ?? ""
      
                      self.list.append(questionTitle) 
      
      
      
      
                  }
              }
          }
      

      【讨论】:

      • 请检查我的回答。您只需在 viewdidLoad 中重新加载 tableview
      【解决方案5】:

      在我的例子中,我删除了前一个数组中的所有项目,然后重新加载。

      我尝试“didset”在数组更改但没有运气的任何时候重新加载。

      所以,干吧

      yourarray.removeall()

      tableview.reloadData()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-14
        • 1970-01-01
        • 2011-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-30
        相关资源
        最近更新 更多