我有一个故事板和视图控制器。每个视图控制器的故事板ID与分配给它的类名相同。像:一个演练视图控制器被分配了WalkThroughVC类,它的故事板Id也是WalkThroughVC。
我在下面创建了一个函数,从storyboard获取视图控制器的实例:
func getViewController<T: UIViewController>() -> T? {
let sb = UIStoryboard(name: "Main", bundle: nil)
sb.instantiateViewControllerWithIdentifier(viewController.rawValue) as? T
}
是否可以推断T的类型?如果是,怎么样?
答案 0 :(得分:0)
我认为你正在寻找。
class ViewControllers
{
class func getViewController<T : UIViewController>(fromStoryboard : String, fromClass : T) -> T?
{
let storyboard = UIStoryboard(name: fromStoryboard, bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("\(fromClass)") as? T
return controller
}
}
答案 1 :(得分:0)
试试这个:
func getViewController<T: UIViewController>() -> T? {
var fullName: String = NSStringFromClass(T.self)
let range = fullName.rangeOfString(".", options: .BackwardsSearch)
if let range = range {
fullName = fullName.substringFromIndex(range.endIndex)
}
let sb = UIStoryboard(name: "Main", bundle: nil)
return sb.instantiateViewControllerWithIdentifier(fullName) as? T
}
答案 2 :(得分:0)
我无法用这种方式推断出来。还没有解决方案, 我使用了以下替代方案:
func getViewController<T: UIViewController>(ofType: T.Type) -> T? {
let sb = UIStoryboard(name: "Main", bundle: nil)
sb.instantiateViewControllerWithIdentifier("\(ofType)") as? T
}
我用它作为:
let viewController = getViewController(WalkThroughVC)