我正从视图控制器A导航到视图控制器B。
@IBAction func companyListTapped(_ sender: Any) {
let viewcontrollerB = Bundle.main.loadNibNamed(String(describing: ListViewController.self),
owner: self,
options: nil)?[0] as! viewcontrollerB
self.navigationController?.pushViewController(viewcontrollerB, animated: true)
}
现在,在导航时,我还想将模型和tableviewcell传递给ViewcontrollerB。为此,我做了一个泛型函数并像这样访问它...
功能是这个。.
func doSomething<M,T>(_ a: M.Type, myType: T.Type) {
print(M.self)
print(T.self)
}
像这样访问...
@IBAction func companyListTapped(_ sender: Any) {
let viewcontrollerB = Bundle.main.loadNibNamed(String(describing: ListViewController.self),
owner: self,
options: nil)?[0] as! ViewControllerB
doSomething(Company.self, myType: CompanyCell.self) -> //Accessed here
self.navigationController?.pushViewController(viewcontrollerB, animated: true)
}
现在,打印M.self
和T.self
给我Company
和CompanyCell
,分别是我的模型和tableviewcell。
但是我如何将这两个值(即Company和CompanyCell)传递给我无法弄清楚的视图控制器B。
希望有人能帮忙...
答案 0 :(得分:0)
在这种情况下,您不需要泛型。您只需要将值从源视图控制器 ListViewController
传递给目标视图控制器 ViewControllerB
class ListViewController: UIViewController {
@IBAction func companyListTapped(_ sender: Any) {
let viewcontrollerB = Bundle.main.loadNibNamed(String(describing: ListViewController.self),
owner: self,
options: nil)?[0] as! ViewControllerB
// Assuming you have companyObject and companyCellObject of type Company and CompanyCell respectively
viewcontrollerB.companyObject = companyObject // replace objects here
viewcontrollerB.companyCellObject = companyCellObject // and here
navigationController?.pushViewController(viewcontrollerB, animated: true)
}
}
class ViewControllerB : UIViewController {
// Assuming you have types with the same name
var companyObject: Company?
var companyCellObject: CompanyCell?
}