【发布时间】:2018-02-04 04:28:30
【问题描述】:
我有一个collectionView 用于在页面之间滚动,在这些整页单元格之一中,我还有另一个带有单元格的collectionView。当点击最里面的collectionView中的一个单元格时,如何执行segue。
【问题讨论】:
-
我的回答有帮助吗?
标签: ios swift uicollectionview segue uistoryboardsegue
我有一个collectionView 用于在页面之间滚动,在这些整页单元格之一中,我还有另一个带有单元格的collectionView。当点击最里面的collectionView中的一个单元格时,如何执行segue。
【问题讨论】:
标签: ios swift uicollectionview segue uistoryboardsegue
您将需要在单元格中的委托,其中包含Collection View,需要在选择特定单元格时通知:
protocol CollectionCellDelegate: class {
func selectedItem()
}
class CollectionCell: UITableViewCell {
weak var delegate: CollectionCellDelegate?
// ...
func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
self.delegate?.selectedItem()
}
}
并且在TableViewController 中,您必须实现该委托才能从它执行segue(您必须从UIViewController 子类执行segue,但UITableViewCell 没有对其进行子类化,这就是您需要委托模式的原因)。
class TableViewController: UITableViewController, CollectionCellDelegate {
// ...
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
// set its delegate to self
cell.delegate = self
return cell
}
func selectedItem() {
// here you can perform segue
performSegue(withIdentifier: "mySegue", sender: self)
}
}
我没有向委托传递任何参数,但您当然可以使用参数来传递 segue 所需的任何信息(例如,选择的集合单元格的 id 等)。
【讨论】:
collectionView == self.innerCollectionView。效果很好,非常感谢您的详细回答。这很有帮助。
当您点击 collectionView 中的项目时,将调用以下委托方法(如果您正确连接所有内容)func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)... 请注意第一个参数是 collectionView 本身。
取决于你如何设置它......
如果您在一个 UIViewController 中有两个 collectionView,那么您可以这样做..
func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
if collectionView == self.innerCollectionView {
// performSegue...
}
}
如果您有两个视图控制器,一个用于外部,另一个用于内部..那么您可以创建使用委托模式来让外部知道选择了哪个项目,并使用该信息进行 segue。
【讨论】:
didSelectItemAt 内调用 performSegue 时,我收到错误“使用未解析的标识符 performSegue”
UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource 协议和 3 个单元格的 MainViewController,其中每个单元格充当一个视图,然后在这三个页面单元格之一中的一个 collectionViewCell 具有相同的协议,其中包含另一个 collectionView。