想象一下我有一个 BaseViewController。然后我有 2 个场景,新建和编辑,两者共享相同的 UI 和大部分逻辑。所以我创建了类 NewViewController 和 EditViewController,子类化 BaseViewController。当我尝试从情节提要中实例化“BaseViewController”时,问题就出现了,因为我想指定哪个实现。
if isEdit {
storyboard.instantiateViewControllerWithIdentifier("baseVCIdentifier") as! EditViewController
} else {
storyboard.instantiateViewControllerWithIdentifier("baseVCIdentifier") as! NewViewController
}
然后我得到一个错误:
无法将“Test.BaseViewController”(0x10ee5e0f0)类型的值转换为“Test.EditViewController”(0x10ee5f000)。
我不想在故事板上同时使用两个 ViewController,因为我不想重做相同的 UI 两次。
您可以使用以下方法执行此操作instantiateViewController(identifier:creator:)
.
我假设您在故事板中有视图控制器,并带有标识符template
。分配给故事板中视图控制器的类应该是超类:
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)
}
}
这里是文档
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)