我自己想通了,在我的情况下,不要使用UICollectionViewLayout (CustomLayout) 使用布局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;
}
delegate之后,调用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。查看此帖子:Horizontally scroll ALL rows of UICollectionView together
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;
}
}
}
}
}