【发布时间】:2020-07-28 19:37:55
【问题描述】:
大家好,
我在从嵌套的 CollectionView 单元格中呈现新视图的逻辑上遇到问题。
在 HomeVC (cell1) 中,我有另一个嵌套了 4 个额外单元格的集合视图。当用户单击相应的单元格时,我想将它们带到另一个视图控制器。图片中单元格 1 下方的绿色箭头表示的工作流程。
实现这一目标的最佳方法是什么?
我已经尝试过这里的建议:Presenting a ViewController from within a CollectionViewCell that is nested in a TableViewCell,但“collectionview 单元格的嵌套”让我失望。
欣赏洞察力!
以下代码已更新
//HomeVC.swift -
class HomeVC: UIViewController {
extension HomeVC: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! SectionCell
return cell
}
//SectionCell.swift - Menu item 1
class SectionCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, CellDelegate {
func aboutCategorySelected(_ indexPath: IndexPath) {
switch indexPath.item {
case 0: //go to new VC1
case 1: //go to new VC2
case 2: //go to new VC3
case 3: //go to new VC4
default: break
}
}
lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.backgroundColor = .init(white: 0.9, alpha: 1)
cv.delegate = self
cv.dataSource = self
return cv
}()
override init(frame: CGRect) {
super.init(frame: frame)
//register nested cv cell
collectionView.register(AboutCell.self, forCellWithReuseIdentifier: "aboutCell")
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item == 2 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "aboutCell", for: indexPath) as! AboutCell
cell.delegate = self
return cell
}
}
//AboutCell.swift - this is the nested cell
protocol CellDelegate {
func aboutCategorySelected(_ indexPath : IndexPath)
}
class AboutCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var delegate: CellDelegate?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.aboutCategorySelected(indexPath)
}
【问题讨论】:
-
在 selectItme 函数中显示一些代码
-
如果您在
tableView中使用collectionView,您应该使用委托,否则您将不得不存储ViewController实例。请显示一些代码以阐明您到目前为止所做的尝试。 -
@Rob - 我已经更新了请求的代码。
标签: ios swift uicollectionview