簡體   English   中英

在 swift 4.0 中將值附加到數組后如何重新加載 tableView

[英]How to reload a tableView once a value has been appended to an array in swift 4.0

在將值附加到數組后,我在重新加載 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)
            }
        }
    }

這段代碼只是向列表數組添加了一個新值,表視圖顯示了列表數組中的內容,但是當我向列表數組添加新內容並在模擬器上運行時,新值沒有

您可以使用屬性觀察者didSet

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

如需更多信息,請單擊此處

您需要為您的 tableview 創建一個插座,一旦您的數據加載,您就可以調用

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

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) 




            }
        }
    }

將新元素添加到list ,在 tableView 上調用insertRowAtIndexPaths:withRowAnimation ,如下所示:

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

就我而言,我刪除了先前數組中的所有項目,然后再次重新加載。

我嘗試“didset”在數組更改但沒有運氣的任何時候重新加載。

所以,簡單地做

yourarray.removeall()

tableview.reloadData()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM