apple/iOS, UIKit, Documentation

iOS SnapKit 공식문서로 공부하기 8탄 (UICollectionView 코드로 구성하기 1편)

lgvv 2021. 8. 22. 13:44

iOS SnapKit 공식문서로 공부하기 8탄 (UICollectionView 코드로 구성하기 1편)

 

UICollectionView를 이번에는 구현해보자.

이것도 스토리보드로만 사용했어서 코드로 아직 흐름이 익숙하지 않다.

 

특히, UICollectionView에서 Delegate랑 DataSource를 전부 올바르게 연결해주었는데, UIcollectionView의 사이즈를 FlowLayoutDelegate에서 실수로 0으로 리턴해서 UI가 그려지지 않는 상황이 있었다.

익숙하지 않아서 그런데, 이를 더 신경쓰자 !

 

 

전체 코드

//
//  UIcollectionView+RxSwiftExample.swift
//  SnapKitPractice
//
//  Created by Lee GeonWoo on 2021/08/21.
//

import Then
import UIKit
import RxSwift
import RxCocoa
import RxDataSources


class ViewController08 : UIViewController {
    
    var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .vertical
        layout.sectionInset = .zero
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .green
        return cv
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(collectionView)
        
        collectionView.delegate = self
        collectionView.dataSource = self
        
        autoLayout()
        //collectionView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width - 100, height: self.view.frame.height - 100 )
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
    }
}

extension ViewController08 : UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        cell.backgroundColor = .blue
        
        return cell
    }
}

extension ViewController08 {
    
    private func autoLayout() {
            collectionView.snp.makeConstraints {
                $0.edges.equalTo(view.safeAreaLayoutGuide)
                    .inset(UIEdgeInsets(top: 0, left: 0, bottom: 200, right: 0))
            }
        }
}

결과물

 

 

 

 

어렵지는 않았는데, 익숙하지 않은게 아직까지도 제일 크다 !