我在以编程方式(没有 Storyboard)从 collectionView 显示 viewController 时遇到了一些问题。我认为这很容易,但由于我对 swift 有点陌生,所以我很难弄明白。我相信 collectionViewCells 默认情况下不是委托(delegate),所以我尝试在 collectionView 类中实现 didSelectItemAt 但仍然没有运气。点击单元格后,我收到了一份打印声明,只是没有任何显示转场。请参阅下面的 collectionViewCell 代码,在此先感谢您!
// 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)
}
}
最佳答案
通常情况下,当你想呈现另一个 View Controller 时,你需要调用这个函数
self.present(yourViewController, animated: true, completion: nil)
但是,您不能在执行打印的地方执行此操作,因为函数 present
仅在 View Controller 中可用。所以现在问题就变成了,如何将您的单元格点击定向到父 View Controller 并传递一个字符串。您有两个选择,您可以创建一个像 this 这样的委托(delegate), 或者做 NSNotificationCenter post call ,第二个更容易。
当你将单元格点击事件传递给你的父 View Controller 时,你可以开始调用上面提到的方法来导航到另一个 View Controller
关于swift - 在没有 Storyboard的情况下从 collectionView 显示 viewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44738333/