简体   繁体   English

从 Storyboard 转换为子类

[英]Cast to a subclass from Storyboard

Imagine i have a BaseViewController.想象一下我有一个 BaseViewController。 Then i have 2 scenarios, New and Edit, where both shares the same UI and the most of logic.然后我有 2 个场景,New 和 Edit,它们共享相同的 UI 和大部分逻辑。 So i created class NewViewController and EditViewController, subclassing BaseViewController.所以我创建了类 NewViewController 和 EditViewController,继承了 BaseViewController。 The problem comes when i try to instantiate "BaseViewController" from the storyboard cause i want to specify which implementation is.当我尝试从情节提要中实例化“BaseViewController”时出现问题,因为我想指定哪个实现。

if isEdit { 
    storyboard.instantiateViewControllerWithIdentifier("baseVCIdentifier") as! EditViewController 
} else {
   storyboard.instantiateViewControllerWithIdentifier("baseVCIdentifier") as! NewViewController 
}

Then i get an error: Could not cast value of type 'Test.BaseViewController' (0x10ee5e0f0) to 'Test.EditViewController' (0x10ee5f000).然后我收到一个错误:无法将“Test.BaseViewController”(0x10ee5e0f0)类型的值转换为“Test.EditViewController”(0x10ee5f000)。

I dont wanto to have both ViewController on the storyboard since i dont want to redo the same UI 2 times.我不想在情节提要上同时拥有两个 ViewController,因为我不想重做相同的 UI 2 次。

You can do this using instantiateViewController(identifier:creator:) .您可以使用instantiateViewController(identifier:creator:)来做到这一点。

I assume you have the view controller in a storyboard, with identifier template .我假设您在故事板中有视图控制器,标识符为template The class assigned to the view controller in the storyboard should be the superclass:故事板中分配给视图控制器的类应该是超类:

let storyboard = UIStoryboard(name: "main", bundle: nil)

let viewController = storyboard.instantiateViewController(identifier: "template") { coder in 
    // this passes us with a coder for the storyboard, we can now init the preferred subclass.

    if useSubclass {
        return SpecialViewController(coder: coder)
    } else {
        return BaseViewController(coder: coder)
    }
}

Here is the documentation这是文档

You can't do that. 你不能那样做。 Instead of sub classing create 'interaction manager' classes, or state manager classes. 代替子类,创建“交互管理器”类或状态管理器类。 The base view controller would then be provided with a manager instance as part of the segue and it would forward all UI interaction to the manager for processing. 然后,基本视图控制器将作为管理的一部分提供一个管理器实例,并将所有UI交互转发给管理器以进行处理。 You then have a single VC in the storyboard as is required and you can supply a new or edit manager. 然后,根据需要在情节提要中只有一个VC,并且可以提供新的或编辑管理器。 The managers can also have specific instance variables which the view controller doesn't care about. 管理器还可以具有视图控制器不关心的特定实例变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM