gpt4 book ai didi

ios - Swift 通用函数来推送任何 View Controller

转载 作者:行者123 更新时间:2023-12-01 22:35:06 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,1)实例化 UIViewController 的子类,2)推送到调用者 UIViewController 的导航 Controller 中。

到目前为止,我有这个:

func pushAnyViewController<T>(viewController:T, storyboardName:String) {
// Instantiate the view controller of type T
guard let nextViewController = UIStoryboard(name: storyboardName, bundle: nil).instantiateViewController(withIdentifier: String(describing: T.self)) as? T else {
return
}

viewController.navigationController.pushViewController(nextViewController, animated: true)
}

这会产生错误

Value of type 'T' has no member 'navigationController'

我不确定是否应该说 T 永远是 UIViewController 的子类。如果是这样的话,我不清楚我在哪里这样做。为此,我想到了:

func pushAnyViewController<T>(viewController:T & UIViewController, storyboardName:String)

但这会产生错误:

Generic parameter 'T' is not used in function signature

Non-protocol, non-class type 'T' cannot be used within a protocol-constrained type

最佳答案

您需要确定T是一个带有 <T:UIViewController> 的 vc

func pushAnyViewController<T:UIViewController>(viewController:T, storyboardName:String) {
guard let nextViewController = UIStoryboard(name: storyboardName, bundle: nil).instantiateViewController(withIdentifier: String(describing: T.self)) as? T else { return }
viewController.navigationController?.pushViewController(nextViewController, animated: true)
}

关于ios - Swift 通用函数来推送任何 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58378967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com