Swift - 将self.navigationController调用到自定义单元类中

Ole*_*pov 5 ios uicollectionviewcell swift

迅速:

我有UICollectionViewController与另一个文件/类UICollectionViewCell

目标是UIViewController从我的自定义单元类推送.

这样的事情:

self.navigationController?.pushViewController(vc, animated: true)
Run Code Online (Sandbox Code Playgroud)

我没有问题实现push didSelectItemAtIndexPathin in UICollectionViewController但我想从注册到我的自定义单元类中执行此操作UICollectionViewController.

当我尝试从自定义单元类推送视图时,遗憾的是我没有访问权限 self.navigationController

此外,我想100%以编程方式这样做.我不使用Storyboard或Nib文件

提前致谢.

ezc*_*ing 7

这是一个坏主意.观点不应该/做那种逻辑.你应该把它留给控制器(这就是MVC模式的内容).

无论如何:

class MyCollectionViewCell: UITableViewCell {
    var myViewController: MyViewController!
}
Run Code Online (Sandbox Code Playgroud)

当单元格出列时你可以这样设置:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    let cell: MyCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(myCellIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
    let nvc: UINavigationController = UIStoryboard(name: "myStoryboard", bundle: nil).instantiateViewControllerWithIdentifier("myNavigationController") as! UINavigationController
    cell.myViewController = nvc.childViewControllers.first as! MyViewController

    return cell
}
Run Code Online (Sandbox Code Playgroud)

并在选择:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    let cell: MyCollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell

    // I don't know where vc comes from
    cell.myViewController.navigationController?.pushViewController(vc, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

尽管如此,我认为没有任何理由,这在任何情况下都没有意义.所以重新考虑你的架构.

通过在纸上绘制实体,可视化实体的通信.你必须画出模型,视图控制器,只有控制器允许"讲"到其他控制器.

看看这个这个


Ita*_*tor 5

我最近也提出了这个问题,我有一种方法来展示 Akhilrajtr 评论,因为它也可能对其他人有帮助。

首先,在你的细胞类中,你需要在文件顶部有一个协议:

protocol YourCellDelegate: NSObjectProtocol{
    func didPressCell(sender: Any)
}
Run Code Online (Sandbox Code Playgroud)

然后在单元格类变量中添加以下内容:

var delegate:YourCellDelegate!
Run Code Online (Sandbox Code Playgroud)

当您在单元内执行某些操作时,触发协议的功能:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    delegate.didPressCell(sender: indexPath)
}
Run Code Online (Sandbox Code Playgroud)

在您的超级主控制器上,您应该符合您创建的委托:

class MyViewController: UIViewController, YourCellDelegate{...}
Run Code Online (Sandbox Code Playgroud)

并且,实现协议的功能,当按下单元格时将触发该协议,就像您之前定义的那样:

func didPressCell(sender: Any){
    let vc = SomeViewController()
    self.navigationController?.pushViewController(vc, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

当然,不要忘记在 cellForItem 函数的单元实例化部分中为您的委托提供参考:

cell.delegate = self
Run Code Online (Sandbox Code Playgroud)