簡體   English   中英

如何在 swift 中以編程方式將 class 設置為 viewcontroller?

[英]how to set class to viewcontroller programmatically in swift?

我有 3 個按鈕、3 個類和 3 個視圖控制器相同的 UI,只有不同的值。 所以我想做 3 個按鈕顯示 1 個 Viewcontrollers 但使用不同的類。

我的邏輯:按下按鈕時 > 設置 class > present vc

@IBAction func openTest(_ sender: Any) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "ExSim")

        // i want to change class here

        present(vc, animated: true)

    }

你有一個基本的誤解。 當您將視圖 controller 添加到 storyboard 時,您告訴 storyboard 您正在添加視圖 controller 的哪個子類,並為其提供唯一標識符。 Any time you instantiate a view controller from your storyboard using a specific identifier, you will always get a view controller of the subclass that's defined in the storyboard. You can't fetch a view controller from a storyboard and then transform it to a different class .

如果你有 3 個不同的屏幕,它們具有相同的 UI 但內容不同,你應該使用 model object 來描述視圖 controller 顯示的內容。 始終使用相同的標識符來實例化它,並根據按下的按鈕將不同的 model object 安裝到其中。 讓視圖 controller 從 model object 加載它的內容到它的視圖中。

如果您不知道 model object 是什么,則需要閱讀 MVC 和 MVVM 等設計模式,並嘗試一些使用 MVC 和 MVVM 設計模式創建應用程序的教程

暫無
暫無

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

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