【问题标题】:How can I expand inner scope value in Swift如何在 Swift 中扩展内部范围值
【发布时间】:2021-07-27 14:01:00
【问题描述】:

我开始开发没多久。所以我的代码有问题。我想在TableView 函数中返回data.count。但我无法获得数据的价值:[DataGroup] in db.collection()。它没有超出db.collection() 范围的价值。那么如何从该范围内获取数据呢?

class RecordGroupViewController: UIViewController, UITableViewDataSource {
    
    let db = Firestore.firestore()
    var data: [DataGroup] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        fetchDataGroup()
    }
    
    func fetchDataGroup() {
        
        db.collection("data").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    do {
                        let docuData = try JSONSerialization.data(withJSONObject: document.data(), options: [])
                        let decoder = JSONDecoder()
                        let groupData: DataGroup = try decoder.decode(DataGroup.self, from: data)
                        
                        self.data.append(groupData)
                    } catch let error {
                        print("---> error: \(error.localizedDescription)")
                    }
                }
            }
        }
        print("\(self.recordGroups.count)")
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
}

【问题讨论】:

    标签: ios swift google-cloud-firestore


    【解决方案1】:

    根据我对您问题的理解,您希望访问数据变量的计数。

    您可以使用 self.data.count 从代码中的任何位置执行此操作

    但是,如果您希望您的 tableView 使用这个新值:

    1. 使用 IBOutlet 将您的 tableview 链接到您的控制器(或者如果您以编程方式实例化它,则创建对它的引用)

    2. 将新数据附加到数据后,调用 self.yourTableViewReference.reloadData(),这将使 tableView 使用新附加的数据调用 dataSource 方法 numberOfRowsInSection。

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      相关资源
      最近更新 更多