tableView嵌套collectionView


首先是自定义collectionView填充的tableViewCell

import UIKit

// 定义一个collectionView,重写初始化大小和布局方法
class TrendsDetailZanCollectionView: UICollectionView {
    
    var indexPath: NSIndexPath!

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}

// collectionView的cellIdentity
let collectionViewCellIdentifier = "zanCollectionCell"

class TrendsDetailZanCVTableViewCell: UITableViewCell {
    
    // tableViewCell中添加collectionView属性
    var collectionView: TrendsDetailZanCollectionView!
    
    // 重写初始化方法,将collectionView加入tableViewCell中
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // 设置布局
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsetsMake(15, 20, 0, 20) //四周间距
        layout.minimumLineSpacing = 27 
        layout.itemSize = CGSizeMake(62, 62) //每一个部分的size
        layout.scrollDirection = UICollectionViewScrollDirection.Vertical
        self.collectionView = TrendsDetailZanCollectionView(frame: CGRectZero, collectionViewLayout: layout) // 初始化collectionView
        self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionViewCellIdentifier)
        self.collectionView.showsVerticalScrollIndicator = false
        self.collectionView.backgroundColor = UIColor.whiteColor()
        self.contentView.addSubview(self.collectionView) // 将collectionView加入tableView中
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    // 注意??重写子视图布局方法,将collectionView的大小设置为和tableViewCell大小相同
    override func layoutSubviews() {
        super.layoutSubviews()
        let frame = self.contentView.bounds
        self.collectionView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height)
    }
    
    // 设置代理刷新数据, 记录下当前collectionView在tableView中的row或者indexPath
    func setCollectionViewDataSourceDelegate(dataSourceDelegate delegate: protocol, index: NSInteger) {
        self.collectionView.dataSource = delegate
        self.collectionView.delegate = delegate
        self.collectionView.tag = index
        self.collectionView.reloadData()
    }

    func setCollectionViewDataSourceDelegate(dataSourceDelegate delegate: protocol, indexPath: NSIndexPath) {
        self.collectionView.dataSource = delegate
        self.collectionView.delegate = delegate
        self.collectionView.indexPath = indexPath
        self.collectionView.tag = indexPath.section
        self.collectionView.reloadData()
    }
}

使用:

// tableView的cell,这里的identity是tableView的cellIdentity
            let zanCellIdentifier = "zanTableViewCell"
                     tableView.registerClass(TrendsDetailZanCVTableViewCell.self, forCellReuseIdentifier: zanCellIdentifier)
            let zanCell: TrendsDetailZanCVTableViewCell?  = tableView.dequeueReusableCellWithIdentifier(zanCellIdentifier, forIndexPath: indexPath) as? TrendsDetailZanCVTableViewCell
            tableView.separatorStyle = .None
            return zanCell!
// 针对当前tableViewCell设置collectionView
 func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if !currentPinglunView {
            if indexPath.row != 0 {
                if let collectionCell: TrendsDetailZanCVTableViewCell = cell as? TrendsDetailZanCVTableViewCell {
                    collectionCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, index: indexPath.row)
                    // 设置collectionView的内容偏移量
                    let index: NSInteger = collectionCell.collectionView.tag
                    // contentOffsetDictionary内容偏移量,在scrollView中有针对collectionView进行设置[因为垂直滑动,key为collectionView,value是x的偏移量]
                    let value: AnyObject? = self.contentOffsetDictionary.valueForKey(index.description)
                    let horizontalOffset: CGFloat = CGFloat(value != nil ? value!.floatValue : 0)
                    collectionCell.collectionView.setContentOffset(CGPointMake(horizontalOffset, 0), animated: false)
                }
            }
        }
    }

写collectionView的代理方法

    // 首先有collectionView的代理方法
    // MARK: - UICollectionView Data source and Delegate
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return zanUserIcons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 注意??这里的cellIdentity和自定义的collectionViewCell的Identity一样!
        let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("zanCollectionCell", forIndexPath: indexPath)
        cell.backgroundColor = UIColor.whiteColor()
        let zanUserIconImageView = UIImageView.init(frame: CGRectMake(10, 0, 44, 44))
        zanUserIconImageView.image = zanUserIcons[indexPath.item]
        let zanuserNameLabel = UILabel.init(frame: CGRectMake(0, 52, 62, 10))
        log.debug(cell.subviews.description)
        // cell的重用,防重复添加子视图
        if cell.subviews.count <= 1 {
            zanuserNameLabel.font = UIFont.systemFontOfSize(10)
            zanuserNameLabel.text = zanuserNames[indexPath.item]
            zanuserNameLabel.textColor = UIColor(hexString: "a8a8a8")
            zanuserNameLabel.textAlignment = .Center
            zanuserNameLabel.font = UIFont.systemFontOfSize(10)
            cell.addSubview(zanUserIconImageView)
            cell.addSubview(zanuserNameLabel)
        }
        // FIXME: - collectionCell高度计算
        let indexP = NSIndexPath.init(forRow: 1, inSection: 0)
        let maY = cell.frame.maxY
        let maX = cell.frame.maxX
        let x = SCREEN_WIDTH - maX
        // 当前子视图在屏幕的最右时增加高度
        if maY >= currentCollectionHeight ||  x < 62 {
            currentCollectionHeight = currentCollectionHeight + maY
            if let cell = detailTableView.cellForRowAtIndexPath(indexP) {
                cell.bounds.size.height = currentCollectionHeight
                detailTableView.reloadRowsAtIndexPaths([indexP], withRowAnimation: UITableViewRowAnimation.Automatic)
            }
        }
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        log.debug("第\(collectionView.tag)行,第\(indexPath.item)个元素")
    }
     // tableView和collectionView代理都继承scrollView代理,滑动触发
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if !scrollView.isKindOfClass(UICollectionView) {
            return
        }
        let horizontalOffset: CGFloat = scrollView.contentOffset.x
        let collectionView: UICollectionView = scrollView as! UICollectionView
        self.contentOffsetDictionary.setValue(horizontalOffset, forKey: collectionView.tag.description)
    }