我有一个数组UIButton
,它们具有唯一的tag
值。当按下给定的按钮时,我要加载并显示一个UIViewController
,它也存储在等长数组中。
要显示的UIViewController
是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)
请告诉我这是否是做这样的事情的不正确的思维过程,并感谢您的帮助。
答案 0 :(得分:7)
您需要实例
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]
答案 1 :(得分:0)
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)
}