Swift - 将self.navigationController调用到自定义单元类中 [英] Swift - Call self.navigationController into custom cell class
问题描述
Swift:
我有UICollectionViewController和另一个文件/类UICollectionViewCell
I have UICollectionViewController with another file/class UICollectionViewCell
目标是推送 UIViewController
来自我的自定义单元格类。
The goal is to push UIViewController
from my custom cell class.
类似这样的内容:
self.navigationController?.pushViewController(vc, animated: true)
我在 UICollectionViewController
中从 didSelectItemAtIndexPath
实现推送没有问题,但我想从自定义单元格执行此操作class注册到我的 UICollectionViewController
。
I have no problems to implement push from didSelectItemAtIndexPath
in UICollectionViewController
but i want to do this from custom cell class registered into my UICollectionViewController
.
当我尝试从自定义单元类推送视图时遗憾的是我没有访问 self.navigationController
When i try to push view from custom cell class unfortunately i don't have access self.navigationController
此外,我想100%以编程方式执行此操作。我不使用Storyboard或Nib文件
Also i want to do this 100% programmatically. I don't use Storyboard or Nib files
提前致谢。
推荐答案
这是一个坏主意。观点不应该/做那种逻辑。你应该把它留给控制器(这就是 MVC-Pattern 的内容)。
This is a bad idea. Views should not have/do that kind of logic. You should leave it with the Controller (that's what the MVC-Pattern is about).
无论如何:
class MyCollectionViewCell: UITableViewCell {
var myViewController: MyViewController!
}
当单元格出列时你可以这样设置:
and when the cell is dequeued you could set it like this:
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
}
以及选择:
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)
}
尽管如此,我认为没有任何理由可以解决这个问题。因此,重新考虑您的架构。
Still, there is no case I can think of, where this would make any sense. So rethink your architecture again.
通过在纸上绘制实体,可视化实体的沟通。您必须绘制模型,视图和控制器,并且只允许控制器与其他人交谈的控制器即可。
Visualize the communication of your entities, by drawing it on a paper. You'll have to draw Models, Views and Controllers and only Controllers are allowed to "talk" to other Controllers.
这篇关于Swift - 将self.navigationController调用到自定义单元类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!