简体   繁体   English

Swift3:转换UIViewController子类失败

[英]Swift3: Casting UIViewController Subclass Fails

I have a ViewController ( BViewController ) that's inheriting from another UIViewController Subclass ( AViewController ). 我有一个ViewController( BViewController ),它继承自另一个UIViewController子类( AViewController )。 (The reason I want to do this is I'm reusing the same view in storyboard 3+ times for different screens.) (我要这样做的原因是我在情节提要中重复使用同一视图3次以上以用于不同的屏幕。)

When I call: 当我打电话时:

let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "AViewController") as! BViewController
        self.show(vc, sender: self)

I get this error: 我收到此错误:

Could not cast value of type 'test.AViewController' (0x10d08b478) to 'test.BViewController' (0x10d08b3f0).

Here are my subclasses, they have nothing in them. 这是我的子类,其中没有任何子类。

class AViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

- --

class BViewController: AViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

The class in Storyboard is set to AViewController because I'm trying to share IBOutlets across all children without recreating the views. 故事板中的类设置为AViewController因为我试图在所有子级之间共享IBOutlets ,而无需重新创建视图。 There is only one View Controller Scene in my UIStoryboard . 我的UIStoryboard只有一个View Controller Scene

According to the answer in this thread, it isn't possible to reuse a single UIViewController Scene with multiple subclasses with UIStoryBoard. 根据该线程的答案,不可能通过UIStoryBoard将单个UIViewController场景与多个子类重用。 It is however possible with nib files. 但是,nib文件是可能的。

How to use single storyboard uiviewcontroller for multiple subclass 如何将单个故事板uiviewcontroller用于多个子类

You probably don't put the right view controller identifier: 您可能没有放置正确的视图控制器标识符:

let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "BViewController") as! BViewController
self.show(vc, sender: self)

(BViewController instead of AViewController) (BViewController而不是AViewController)

EDIT : Here's an example: I have a SignupVC view controller in my storyboard, but its storyboard ID is "signup_vc" 编辑 :这是一个示例:我的情节提要中有一个SignupVC视图控制器,但其情节提要ID为“ signup_vc”

在此处输入图片说明

您必须在情节提要中将视图控制器的类设置为BViewController

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

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