从collectionView显示viewController没有故事板

问题描述:

我有一些麻烦,从一个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) 
    } 

} 

通常,当你想提出另一种观点controoler ,您需要调用此功能

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

但是,由于功能present仅在视图控制器中可用,因此无法在打印位置执行此操作。所以现在问题变成了,如何将你的单元格点击到父视图控制器并传递一个字符串。你有两个选择,你可以创建一个代表this,或者做一个NSNotificationCenter post call,第二个更容易。

当您通过单击单元格事件到父视图控制器,你就可以调用上面提到的方法来导航到我不是在所有用故事板另一种观点认为controoler

+0

谢谢,但它现在给我的错误消息“价值的类型'PlanningCell'没有会员'存在'” – user3708224

+0

@ user3708224更新了我的答案 –

+0

好的,谢谢。我会研究这些选项。 – user3708224

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

答复已更新。 –