目前负荷视图 - 控制加载视图 - 控制与同一nibname我使用的代码如下用笔尖泛型
let recommendationVC : RecommendationVC = RecommendationVC(nibName: "RecommendationVC", bundle: nil)
我感到指定nibname是unncessary,因为它是一样的控制器名称。所以我决定使用泛型和使用泛型
protocol NibIdentifiable {
static var nibNameIdentifier: String { get }
}
// MARK: - Indentifies each storyboard from its classname.
extension NibIdentifiable where Self: UIViewController {
static var nibNameIdentifier: String {
return String(describing: self)
}
}
extension UIViewController :NibIdentifiable
{
}
extension UIViewController {
func instantiate<Controller: UIViewController>(_: Controller.Type) -> Controller where Controller: NibIdentifiable {
guard let controller = Self(nibName:Controller.nibNameIdentifier,bundle:nil) as? Controller else {
fatalError("Could not dequeue cell with identifier: \(Controller.nibNameIdentifier)")
}
return controller
}
}
推断类型和笔尖的名字,但在试图建立一个VC的实例,
let recommendationVC :RecommendationVC = UIViewController.instantiate()
收到错误 泛型参数“控制器”不能推断
这种方法有什么问题?
让recommendationVC:RecommendationVC = RecommendationVC.instantiate( ) 请试试这个 –
@KonstantinKryzha novsky我试过了。面临同样的问题 –
当笔尖名称与班级名称相同时,您甚至不必指定它。只要'let recommendationVC = RecommendationVC()'应该可以正常工作。 – dan