【问题标题】:iOS (Swift) - Array of UIViewControllersiOS (Swift) - UIViewControllers 数组
【发布时间】:2018-12-20 09:30:38
【问题描述】:

我有一个数组 UIButtons,它有一个唯一的 tag 值。当按下给定按钮时,我想加载并呈现一个UIViewController,它也存储在一个等长的数组中。

要呈现的UIViewControllers 是UIViewController 的子类的子类:

class AViewController: UIViewController {}
class BViewController: AViewController {}
class CViewController: AViewController {}
class DViewController: AViewController {}
// ... etc.

我尝试使用以下方法存储 AViewController 子类的数组:

private var array: [AViewController] = [BViewController.self, CViewController.self, DViewController.self]

但我收到错误无法将类型“[BViewController].Type”的值转换为第一个元素的指定类型“[AViewController]”

然后我将使用以下内容呈现BViewController(例如):

let ViewController = array[button.tag].self
var viewController: AViewController
viewController = ViewController.init()
viewController.transitioningDelegate = self
viewController.modalPresentationStyle = .custom
present(viewController, animated: true)

请让我知道这是否是做这种事情的不正确的思考过程,谢谢你的帮助。

【问题讨论】:

    标签: ios arrays swift uiviewcontroller presentmodalviewcontroller


    【解决方案1】:

    你需要实例

    private var array: [AViewController] = [BViewController(), CViewController(), DViewController()]
    

    如果 vcs 在 IB 中,那么你会这样做

    let b = self.storyboard!.instantiateViewController(withIdentifier: "bID") as! BViewController
    let c = self.storyboard!.instantiateViewController(withIdentifier: "cID") as! CViewController 
    let d = self.storyboard!.instantiateViewController(withIdentifier: "dID") as! DViewController
    

    然后

    array = [b,c,d]
    

    【讨论】:

    • 感谢您的建议。这会不会占用大量内存,因为我有大约 10 个 AViewController 的子类,每个子类的大小都相当大?再次感谢。
    • 是的,这是一项繁重的工作,您可以创建一个 var 来跟踪当前索引,然后在需要时加载 vc,而无需创建该数组或将其设为故事板 ID 数组跨度>
    • 谢谢。我以编程方式写这个,所以没有故事板或segues。这比使用 segues 更有用吗?在调用 viewDidLoad 函数之前,视图控制器中的许多 UIButtons 都会被初始化...
    • 您可以即时创建链接,例如在函数中使用 Int 开关,该函数采用索引并返回 vc,例如 1 返回 BViewController 等等,以便在需要时创建它们
    【解决方案2】:
    lazy var VCArray :[UIViewController] = {
        return [VCinst(name: "firstVC"),VCinst(name: "secondVC"), VCinst(name: "thirdVC")]
    }()
    
    func VCinst(name:String) -> UIViewController {
           return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: name)
    }
    

    【讨论】:

    • 希望它能解决问题,但请添加对代码的解释,以便用户完全理解他/她真正想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多