目前負荷視圖 - 控制加載視圖 - 控制與同一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