gpt4 book ai didi

ios - 如何在调用 tableView 之前更新变量

转载 作者:行者123 更新时间:2023-11-28 15:08:30 24 4
gpt4 key购买 nike

在下面的代码片段中,SecondViewController 是通过 FirstViewController 的 segue 打开的(第一个 View Controller 的内容未提供,因为与问题无关)。 SecondViewController 包含一个 tableView 但在显示时它是空的(serviceMain 数组),我已经验证在 tableView 函数中调用数组并且数组确实是空的(print(serviceMain .count)) 在 B block 注释中。但是serviceMainViewDidLoad(A block 注释)中构造和调用时实际上并不为空。

我尝试了 ViewWillAppear 而不是 ViewDidLoad,它产生了相同的结果。

我确信 segues 的工作方式一定与某些事情有关,因为我可以使用 prepare(for segue:sender:)FirstViewController 传递数据我已经完成了 companyName 并且此数据很好。我可以从 FirstViewController 中更新 serviceMain 并将数据传递给 SecondViewController,但我希望我可能遗漏了一些东西并且它可以完成在 SecondViewController 中。非常感谢大家

import UIKit

class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var serviceMain: [Service] = []
var companyName: String = "" // this value is updated with prepare from another ViewController via segue

@IBOutlet var mobileTableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()
Service.parseData(providerName: companyName, id: 999) { (services: [Service]) in
for service in services {
self.serviceMain.append(service)
}
// (A) - serviceMain.count is returning a correct value:
print("number of elements in serviceMain", serviceMain.count, "calling in viewDidLoad")
}
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// (B) - serviceMain.count is returning 0:
print("number of elements in serviceMain", serviceMain.count, "calling in tableView:")
return serviceMain.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = mobileTableView.dequeueReusableCell(withIdentifier: "mobileServiceCell", for: indexPath)
let serviceIndividualRow = serviceMain[indexPath.row]
cell.textLabel?.text = serviceIndividualRow.name!

return cell
}
}

最佳答案

试试 didSet。一旦它被“设置”,就会在 viewDidLoad、viewWillLoad 等之前被调用。

var companyName: String? = "" {
didSet {
// DO SOMETHING
}
}

编辑您对延迟的评论:

当您获取数据时,您可能想尝试在其中添加您的获取数据代码:

DispatchQueue.global(qos: .userInteractive).async {
// FETCH DATA FROM SERVER
}

此外,为了加快速度,无论您在何处重新加载 tableViews/collectionViews,您都可能希望将其添加到其中,如下所示:

DispatchQueue.main.async {
self.tableView.reloadData()
}

关于ios - 如何在调用 tableView 之前更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com