有沒有辦法通過實例化 - 設置 - 推一個視圖控制器使用像這樣的輔助方法,但同時避免向下轉換?推送UIViewController的幫手方法
func pushController(id: String, setup: (_ vc: UIViewController) ->()) {
if let vc = storyboard?.instantiateViewController(withIdentifier: id) {
setup(vc)
navigationController?.pushViewController(vc, animated: true)
}
}
// usage
pushController(id: "Cars") { vc in
(vc as! CarsVC).brand = "BMW"
}
// ...want to avoid downcasting
vc.brand = "BMW"
周圍有鑄造沒有辦法,因爲'故事板.instantiateViewController(withIdentifier:)'總是返回類型'UIViewController',你要麼投的對象在'pushController(ID:)'方法或施放'storyboard?.i的返回值nstantiateViewController(withIdentifier:)'並且有專門的幫手。 – JAL