我有兩個視圖控制器(VC-1,VC-2)。 視圖控制器1有一個表視圖,該表視圖由4個集合視圖組成。我想導航到新的VC(VC-2)。但在集合視圖的 didSelect 方法中無法得到 "self.storyboard.instantiateViewController"。 所以現在我怎樣才能導航到VC-2呢
uj5u.com熱心網友回復:你應該使用委托。你可以創建一個協議并定義一個路由的方法,然后把它實作在VC1中
。CodePudding
你可以使用下面的示例代碼。 這段代碼使用的是封閉式語法
class FirstVC。UIViewController, UITableViewDataSource, UITableViewDelegate{
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView。UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell_Identifier") as! TableCell
cell.configureCell(data: ["Your", "Data"])
cell.didSelectRow = { data in >。
//goto second view controller
let vc = self.storyboard? .instantiateViewController(withIdentifier: "SecondVC")
self.navigationController?.pushViewController(vc! , animated: true)
}
return cell
}
}
class TableCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate{
@IBOutlet weak var colView: UICollectionView!
var didSelectRow: ((_ data: String) -> Void)? = nil //Closure
var arrData = [String]()
func configureCell(data: [String]) {
//設定CollectionView資料。
self.arrData = data
self.colView.reloadData()
}
func collectionView(_ collectionView。UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.arrData.count
}
func collectionView(_ collectionView。UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL_IDENTIFIER", for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let data = self.arrData[indexPath.row]
didSelectRow?(data)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/311709.html
標籤:
