CollectionView分组,组头高度自适应

需求:选中答题卡中一个选项,下次进入答题卡,选中的题在屏幕中.


实现的页面

因为要实现选中的滚动居中效果,使用tableView在cell内部添加Button的方式很难实现(尝试无果后放弃),只能使用CollectionView来实现.具体实现代码:

1.自定义header和cell

collectionView.register(AnswerCardCollectionViewCell.self, forCellWithReuseIdentifier: "answerCardCellId")

collectionView.register(AnswerCardHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")

// DataSource
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "answerCardCellId", for: indexPath) as! AnswerCardCollectionViewCell

        cell.configData(model: sourceArray[indexPath.section].userAnswers[indexPath.row], fromePage: type, index: String(indexPath.row + 1))

        return cell

    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if kind == UICollectionView.elementKindSectionHeader {

            let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! AnswerCardHeaderView

            header.configHeaderData(model: sourceArray[indexPath.section])

            return header

        } else {

            return UICollectionReusableView()

        }

    }

2.计算headView的高

// 实现UICollectionViewDelegateFlowLayout代理方法

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

        var height: CGFloat = 0

        if (sourceArray[section].titel ?? "").isEmpty {

            return CGSize(width: SCREEN_WIDTH, height: height)

        } else if (sourceArray[section].projectInro ?? "").isEmpty {

            height = 56

            return CGSize(width: SCREEN_WIDTH, height: height)

        } else {

            let proInroH = (sourceArray[section].projectInro ?? "").getHeight(font: UIFont.systemFont(ofSize: 14), width: SCREEN_WIDTH - 40, lineSpacing: 1.5)

            height = 66 + proInroH

            return CGSize(width: SCREEN_WIDTH, height: height)

        }

    }

3.滚动CollectionView

collectionView.scrollToItem(at:IndexPath(item: row, section: section), at: .centeredVertically, animated:false)

你可能感兴趣的:(CollectionView分组,组头高度自适应)