[iOS/Swift] Compositional Layout - Grid

민니·2022년 12월 8일
0

iOS

목록 보기
22/22

사실 찐은 section이 여러 개고, 걔네마다 레이아웃이 다른 거지만!
일단 grid 형태부터 차근차근 만들어 보기로 ;ㅅ;


Grid 기본

item이 90개인 grid 형태의 collectionView
각 행은 5개의 item으로 이루어져 있음
위 이미지처럼 빨간색 영역은 item 1개, 파란색 영역은 group 1개

compositional layout에서 각 구성들의 크기를 지정하는 방법은 3가지

1. container와의 비율
2. point로 직접 지정
3. 추정

첫 번째 방법을 이용해서 표현해 보면,
item의 container은 group이다
따라서 item의 너비 = container(group) 너비의 20%
item의 높이 = container(group) 높이와 동일(100%)

group의 container은 section이다
group의 너비 = container(section) 너비와 동일(100%)
group의 높이 = container(section) 너비의 20%(item이 정사각형이 됨)

이를 코드로 나타내면 된당

private func createLayout() -> UICollectionViewLayout {
        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.2),
                                              heightDimension: .fractionalHeight(1.0))
        let item = NSCollectionLayoutItem(layoutSize: itemSize)
        
        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                               heightDimension: .fractionalWidth(0.2))
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
        
        let section = NSCollectionLayoutSection(group: group)
        
        let layout = UICollectionViewCompositionalLayout(section: section)
        
        return layout
}

compositional layout을 구현하는 데 사용한 코드

private func config() {
        view.backgroundColor = .white
        
        let cellRegisteration = UICollectionView.CellRegistration<GridCollectionViewCell, Int> { cell, indexPath, itemIdentifier in
            cell.nameLabel.text = "\(itemIdentifier)"
        }
        
        dataSource = UICollectionViewDiffableDataSource(collectionView: gridCollectionView, cellProvider: { collectionView, indexPath, itemIdentifier in
            return collectionView.dequeueConfiguredReusableCell(using: cellRegisteration, for: indexPath, item: itemIdentifier)
        })
        
        var snapshot = NSDiffableDataSourceSnapshot<Section, Int>()
        snapshot.appendSections([.main])
        snapshot.appendItems(Array(0..<90))
        dataSource.apply(snapshot, animatingDifferences: true)
}

데이터 구성은 일케 해 줬고, 데이터는 숫자 0~89까지로 지정!


Inset 주기

item.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5)

짜잔 ✨
구분하기 쉽게 collectionView의 배경색색은 임의로 노랑으로 지정해 주었음
이런 식으로 group/section 모두 contentInset을 줄 수 있고, interItemSpacing 도 사용 가능


group당 item 수 지정하기

WWDC 2019에서 NSCollectionLayoutGroup 을 사용할 때 count 파라미터를 사용하면 앞의 itemSize를 고려하지 않고 count에 의해 재정의된다고 봤는데 얘가 사라지고 새로운 메소드가 만들어져 있더라…

암튼 한 group에서 몇 개의 item을 보여줄지를 결정한다!

let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, repeatingSubitem: item, count: 2)

코드를 이런 식으로 수정해 주었더니 왼쪽처럼 돼서(오른쪽처럼 될 줄)

let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5),
                                              heightDimension: .fractionalHeight(1.0))

itemSize도 같이 수정해 주었다!



👩🏻‍💻 Grid 코드 보기
👩🏻‍💻 List 코드 보기

List 형태도 다른 건 다 같고, item 사이즈만 조정해서 만들었다.


0개의 댓글