1

我有一些麻煩,從一個collectionView以編程方式顯示viewController(沒有故事板)。我會認爲這很容易,但我有一些困難,因爲我對swift有點新穎。我相信collectionViewCells默認情況下不是委託,因此我嘗試在collectionView類中實現didSelectItemAt,但仍然沒有運氣。點擊該單元格時,我收到一個打印語句,只是沒有任何顯示繼續。請參閱下面的collectionViewCell代碼,並提前致謝!從collectionView顯示viewController沒有故事板

// collectionViewCell class 
class PlanningCell: BaseCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { 

    lazy var collectionView: UICollectionView = { 
     let layout = UICollectionViewFlowLayout() 
     let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) 
     cv.dataSource = self 
     cv.delegate = self 
     return cv 
    }() 

    //collectionViewCell variables 
    var plannedPlaces = [CurrentPlanner]() 
    let cellId = "cellId" 

    var basePlanningCell: BasePlanningCell! 

    override func setupViews() { 
     super.setupViews() 
     addSubview(collectionView) 

     collectionView.register(BasePlanningCell.self, forCellWithReuseIdentifier: cellId) 
    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return plannedPlaces.count 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! BasePlanningCell 
     cell.currentPlanner = plannedPlaces[indexPath.item] 
     return cell 
    } 

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     print("did tap") 
     let plannersDetailVC = PlanningPlaceDetailsVC() 
     plannersDetailVC.navigationTitle = plannedPlaces[(indexPath.row)].planningPlace 
     // below I am receiving the use of unresolved identifier "show" error 
     show(plannersDetailVC, sender: self) 
    } 

} 

回答

0

通常,當你想提出另一種觀點controoler ,您需要調用此功能

self.present(yourViewController, animated: true, completion: nil) 

但是,由於功能present僅在視圖控制器中可用,因此無法在打印位置執行此操作。所以現在問題變成了,如何將你的單元格點擊到父視圖控制器並傳遞一個字符串。你有兩個選擇,你可以創建一個代表this,或者做一個NSNotificationCenter post call,第二個更容易。

當您通過單擊單元格事件到父視圖控制器,你就可以調用上面提到的方法來導航到我不是在所有用故事板另一種觀點認爲controoler

+0

謝謝,但它現在給我的錯誤消息「價值的類型'PlanningCell'沒有會員'存在'」 – user3708224

+0

@ user3708224更新了我的答案 –

+0

好的,謝謝。我會研究這些選項。 – user3708224

0
let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "VCIdentifier") as! PlanningPlaceDetailsVC 
     present(vc, animated: true, completion: nil) 

不要忘記設置PlanningPlaceDetailsVC 標識符

更新爲VC通過代碼設置好的:

let vc : UIViewController = PlanningPlaceDetailsVC() 
self.presentViewController(vc, animated: true, completion: nil) 
+0

。 – user3708224

+0

答覆已更新。 –