在UICollectionViewCell

时间:2018-06-18 17:48:10

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我正在尝试使用自定义布局(MyCustomLayout)来嵌入另一个UICollectionView(containerCollectionView)的UICollectionViewCell(containerCollectionViewCell)中的UICollectionView(embeddedCollectionView)。 embeddedCollectionView中每个单元格的高度各不相同,需要根据给定单元格的内容动态确定。

为了实现这一点,我试图设置一个布局委托(MyLayoutDelegate),可以在MyCustomLayout的prepare()方法中调用...这个委托将根据每个单元格的高度来计算它的数据/内容,类似于此raywenderlich.com教程中描述的内容:https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2)。

这是协议......

protocol MyLayoutDelegate: class {
  func collectionView(_ collectionView:UICollectionView, heightForCellAtIndexPath indexPath:IndexPath) -> CGFloat 
}

在自定义布局的prepare()方法中,调用委托来获取单元格的变量高度......

override func prepare() {
  …
  for item in 0 ..< collectionView.numberOfItems(inSection: 0) { 
 …       
    let cellHeight = delegate.collectionView(collectionView, heightForCellAtIndexPath: indexPath)
 …
 …
    }
}

我遇到的困难是MyCustomLayout的prepare()方法在实际委托被设置之前被调用,因此在调用prepare()时委托是nil ...我不确定是在调用prepare()方法之前设置布局委托的适当位置。

if let layout = collectionView?.collectionViewLayout as? MyCustomLayout {
  layout.delegate = self
}

我已成功使用此自定义布局和委托方法与其自己的VC中的不同UICollectionView,只需在VC的viewDidLoad()方法中设置布局委托。但我还没能找到在这个嵌套集合视图上设置布局委托的合适位置。

为了尝试使用嵌套视图执行类似的操作,我尝试通过为此嵌入式UICollectionView创建单独的UICollectionViewController来重新设计UI,嵌入在UICollectionViewCell中的UIContainerView中,但这会导致非法配置编译错误,指示“容器视图不能放在运行时重复的元素”。所以设计不会起作用。

有没有人对我在哪里设置这个嵌套集合视图的布局委托有任何建议或见解?

可以共享其他代码和故事板视图,以更好地说明我尝试实现的目标,如果这将有所帮助。

提前感谢您的帮助!

0 个答案:

没有答案