在运行时更改集合视图单元格宽度

我正在创建一个EPG(电子节目指南); 检索我使用JSON的程序信息。 对于设计,我在左半部分有一个用于频道徽标和名称的表格视图,在右半部分有一个用于该频道的所有电视节目的集合视图。 问题是,对于每个节目,集合视图行必须具有不同的宽度,这取决于节目的持续时间。

我正在基于这个名为EPG Grid的奇妙示例构建它

但在此示例中,所有通道先前都加载到一个arrays中。 如果通道列表很短,这可以正常工作,但在我的情况下列表非常大,所以我需要加载tableView:cellForRowAtIndexPath:每个通道tableView:cellForRowAtIndexPath: ,然后创建具有指定宽度的布局。

有什么想法吗?

我想通了我自己,事情是在我的情况下不使用UICollectionViewLayoutUICollectionViewLayout )使用布局Flow并在tableView添加collectionView ,如下所示:

在此处输入图像描述 在此处输入图像描述

然后在tableView每一行委托collectionView

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell cell.collectionView.delegate = self cell.collectionView.dataSource = self cell.collectionView.tag = indexPath.row cell.tag = 100 + indexPath.row; return cell; } 

委托之后,调用方法collectionView:sizeForItemAtIndexPath ,在此方法中,您必须使用indexPath计算检索数据的宽度或高度

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { //Calculation of width based on indexPath //... return CGSizeMake(width, 89) } 

最后,为了使所有单元格的滚动均匀,同时使用方法scrollViewDidScroll 。 检查这篇文章: 水平滚动所有UICollectionView行

 func scrollViewDidScroll(scrollView: UIScrollView) { var ret: Bool = false; if (self.lastContentOffset > scrollView.contentOffset.x) { ret = true; } else if (self.lastContentOffset < scrollView.contentOffset.x) { ret = true; } if(scrollView.isKindOfClass(UICollectionView) && ret) { self.lastContentOffset = scrollView.contentOffset.x; for var i = 0; i < data.count; i++ { let cell = self.view.viewWithTag(100 + i) as? ChannelTableViewCell; if(cell != nil) { let collectionCell: UICollectionView? = cell?.collectionView; if(collectionCell != nil) { collectionCell!.contentOffset = scrollView.contentOffset; } } } } }