簡體   English   中英

Swift 4如何在ViewControllers和ContainerViews之間傳遞數據?

[英]Swift 4 How to pass data between ViewControllers and ContainerViews?

我有3個ViewController:ViewController A和ViewController B,以及Controller C,它實際上是由兩個UIView組成的ContainerView

我的故事板

如上圖所示,ViewController C具有清晰的背景,因此可以在ViewController A和B的UIView中看到“測試標簽”。

當我從ViewController A向上滑動以轉到ViewController B時,我希望能夠執行一些動畫(淡入/淡出,翻譯,更改文本等)。 假設我要將文本從“測試標簽”更改為“一些新文本”,問題是,一旦我進入ViewController B,就會收到“在展開可選值時意外發現nil”錯誤。

為什么我沒有得到零,如何正確更改標簽文本?

這段代碼似乎很有意義,但是我做錯了:

let containerViewController = ContainerViewController()
        containerViewController.testLabel.text = "Some new text"

我也嘗試過:

let containerViewController = storyboard?.instantiateViewController(withIdentifier: "containerViewController") as! containerViewController


        containerViewController.testLabel.text = "Some new text"

我是否必須在ViewController A的重寫功能prepare中添加某些內容?

您可以給從容器到視圖控制器C的嵌入序列一個標識符,讓它說embedSegueFromBToC然后在父控制器中為embedSegueFromBToC做准備中捕獲實際的ViewController C ,比如說B

因此,在B viewController中添加以下代碼:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "embedSegueFromBToC" {
            if let viewControllerC =  segue.destination as? ViewControllerC {
                viewContrllerC.loadViewIfNeeded() // you might need this since the need to access the testLabel which a UI component that need to be loaded
                viewControllerC.testLabel.text = "Some new text"
            }
        }
    }

正確,您必須在原始視圖控制器中使用prepare(for segue:..)重寫,它將傳遞給ViewController B的實例作為segue.destination。

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if let viewControllerB = segue.destination as? ViewControllerB
    {
        viewControllerB.testLabel.text = "Some new text"
    }
}

查看本教程以獲取更多信息: https : //learnappmaking.com/pass-data-between-view-controllers-swift-how-to/

暫無
暫無

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

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