CollectionView - 每个部分中的列数不同

时间:2018-02-27 19:54:01

标签: ios swift uicollectionview uicollectionviewlayout

我想拥有以下示例的集合视图。但是无法弄清楚如何以它的方式实现它。它在第一部分有3列,在第二部分有2列。

enter image description here 请帮忙!!!

2 个答案:

答案 0 :(得分:3)

这是一个完整的示例,根据部分显示不同的单元格大小。

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    let data: [ (headerTitle: String, items: [String]) ] = [
        // Section 1
        ("Header 1", ["cell1", "cell2", "cell3", "cell4", "cell5", "cell6"]),

        // Section 2
        ("Header 2", ["cell1", "cell2", "cell3", "cell4", "cell5", "cell6"])
    ]

    // Create collectionView
    lazy var collectionView: UICollectionView = {
        let cv: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: self.layout)
        cv.contentInset.left = self.layout.minimumInteritemSpacing
        cv.contentInset.right = self.layout.minimumInteritemSpacing

        // register cell class
        cv.register(Cell.self, forCellWithReuseIdentifier: Cell.id)

        // register header
        cv.register(Header.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: Header.id)

        // set data source
        cv.dataSource = self
        cv.delegate = self

        return cv
    }()

    // Create collection view layout
    lazy var layout: UICollectionViewFlowLayout = {
        let l: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        l.minimumInteritemSpacing = 5 // horizontal space between cells
        l.minimumLineSpacing = 5 // vertical space between cells

        return l
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.backgroundColor = .white
        view.addSubview(collectionView)
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        collectionView.frame = view.bounds
    }

    var threeRowsSize: CGSize {
        // Tell layout to put 3 items in a row
        let width: CGFloat = collectionView.bounds.width/3 - (2 * layout.minimumInteritemSpacing)
        return CGSize(width: width, height: width)
    }

    var twoRowsSize: CGSize {
        // Tell layout to put 2 items in a row
        let width: CGFloat = collectionView.bounds.width/2 - (2 * layout.minimumInteritemSpacing)
        return CGSize(width: width, height: width)
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return data.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data[section].items.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.id, for: indexPath) as! Cell
        cell.textLable.text = data[indexPath.section].items[indexPath.row]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: Header.id, for: indexPath) as! Header

        header.textLable.text = data[indexPath.section].headerTitle

        return header
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.bounds.width, height: 50)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,   sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            return threeRowsSize//threeRowsSize
        }
        return twoRowsSize
    }

    // Cell
    final class Cell: UICollectionViewCell {
        static let id: String = "cellId"

        let textLable: UILabel = UILabel()

        override init(frame: CGRect) {
            super.init(frame: frame)
            textLable.textAlignment = .center
            contentView.addSubview(textLable)
            textLable.backgroundColor = .lightGray
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        override func layoutSubviews() {
            super.layoutSubviews()
            textLable.frame = bounds

            // Make it somewhat circular
            textLable.layer.cornerRadius = textLable.bounds.width/3
            textLable.layer.masksToBounds = true
        }
    }

    // Header
    final class Header: UICollectionReusableView {
        static let id: String = "headerId"

        let textLable: UILabel = UILabel()

        override init(frame: CGRect) {
            super.init(frame: frame)
            backgroundColor = .cyan
            textLable.textAlignment = .left
            addSubview(textLable)
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        override func layoutSubviews() {
            super.layoutSubviews()
            textLable.frame = bounds
        }

    }
}

答案 1 :(得分:1)

覆盖sizeForItemAtIndexPath并执行以下操作:

- (NSInteger)itemPerRow:(UICollectionView *)collectionView forSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }

    return 2;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    NSInteger itemsPerRow = [self itemsPerRow:collectionView forSection:indexPath.section];

    CGFloat itemSpacing = ((UICollectionViewFlowLayout *)collectionViewLayout).minimumInteritemSpacing;

    UIEdgeInsets insets = [self collectionView:collectionView layout:collectionViewLayout insetForSectionAtIndex:indexPath.section];

    CGFloat width = (collectionView.bounds.size.width - (itemSpacing * (itemsPerRow - 1))) - (insets.left + insets.right);
    width /= itemsPerRow;
    return CGSizeMake(floor(width), floor(width));
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {

    return UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0);
}

根据项目间距以及部分插入,根据部分中每行的项目数计算每个项目的大小。它将“放置”itemWidth以确保X项适合(由于舍入问题)。