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

标签 ios swift

在下面的代码片段中,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/

相关文章:

ios - 使用 Firebase 扁平化数据

ios - UITableView 高度等于 contentSize 高度

iphone - 代码: "uniqueIdentifier deprecated"

objective-c - iOS 应用程序中的 sinf() 和 cosf()

ios - Xcode 8 Assets 目录向量编译错误 : actool failed with exit code 255

ios - 使用搜索显示 Controller 时隐藏普通 UITableView

ios - 当我使用自动布局选择每个单元格的高度(因此它们是动态的)时,它通常可以工作,但有些单元格有点短。为什么是这样?

ios - iOS 7 中 UISearchBar 中的 UITextField

swift - 在 Swift 的协议(protocol)扩展中访问嵌套在结构中的枚举变量

ios - UITextView 和单元格根据 textview 的内容动态更新高度?