gpt4 book ai didi

ios - 为什么带有 subview Controller 的 UIViewController 有时会返回children[0].isEmpty = true?

转载 作者:行者123 更新时间:2023-11-30 10:54:09 28 4
gpt4 key购买 nike

当我尝试使用self.children[0].currentInfo = UpdatedInfo将updatedInfo从父UIViewController传递到嵌入/子UIViewController时,出现了这个问题。事实证明,在父 View Controller 的“普通”函数中,这工作得很好。但是从父 View Controller 中的委托(delegate)函数内部,它使程序崩溃了。显然,有时 - 但并非总是 - self.children.isEmpty = true 在委托(delegate)函数内。

在不知道其原因的情况下,我不知道如何可靠地使用 self.children 来传递信息。但我不想仅仅因为我不理解它而避免使用它。任何见解将不胜感激。

由于我的应用程序引入了太多复杂的因素,我决定通过创建一个非常简单的“玩具”应用程序来检查问题。这是我所拥有的(代码位于 Storyboard屏幕截图下方):

enter image description here

在MainViewController文件中,有

import UIKit

class MainViewController: UIViewController, InfoDelegate {

var text = "Text from MainViewController"

override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.lightGray
printString("Text from MainViewController's viewDidLoad")
}

// Ordinary func
func printString(_ string: String) {
print(string)
print("In printString, self.children.isEmpty is \(self.children.isEmpty)")
}

// Delegate func
func messageString(_ string: String) {
print(string)
print("In messageString, self.children.isEmpty is \(self.children.isEmpty)")
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if let textViewController = segue.destination as? TextViewController {
textViewController.text = text
textViewController.delegate = self
}
}
}

在 TextViewController 中,有

import UIKit

protocol InfoDelegate: AnyObject { func messageString(_ string: String) }

class TextViewController: UIViewController {

@IBOutlet weak var textView: UITextView!
var text = "Text from TextViewController"
weak var delegate: InfoDelegate?

override func viewDidLoad() {
super.viewDidLoad()
textView.text = text
delegate?.messageString("Text from TextViewController's InfoDelegate")
}
}

最佳答案

在加载目标 View Controller 的 View 之前,会调用 prepare(for:sender:) 方法。它也可能在 subview Controller 安装到父 View Controller 的 children 数组之前被调用。 (我还没有测试过这一点,但它是有道理的。创建目的地后立即调用 prepare(for:sender:) ,以便您有机会进行早期设置。)

我建议将 didSet 添加到您 child 的 delegate 属性中并对其进行测试。将测试 amIAChildYet 方法添加到您的委托(delegate)协议(protocol)中,并在 subview Controller 的委托(delegate)属性的 didSet() 方法中调用它,以查看设置的顺序。

关于ios - 为什么带有 subview Controller 的 UIViewController 有时会返回children[0].isEmpty = true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54146846/

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