📚UICollectionView 간단 사용하기

sanghee·2021년 10월 4일
1

👏iOS 스터디

목록 보기
9/10

목표

UICollectionView를 활용하여 아래의 화면을 만들어본다.

1. 컬렉션셀 만들기

셀에 이미지뷰를 넣고 셀 전체를 덮도록 한다.

import SnapKit
import UIKit

class CustomCollectionCell: UICollectionViewCell{
    static let identifier = "CustomCollectionCell"
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setImageView()
    }

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

    let imageView: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()

    func setImageView(){
        backgroundColor = .systemGroupedBackground
        
        addSubview(imageView)
        
        imageView.snp.makeConstraints {
            $0.top.bottom.left.right.equalToSuperview()
        }
    }
}

뷰컨트롤러에서 컬렉션뷰 넣기

images는 테스트를 위한 이미지 배열이다. columns는 열이 몇개인지, space는 사이간격이 몇인지를 나타내는 상수이다.

함수에 대한 자세한 사항은 주석으로 처리하였다.

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    let images = ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg", "g.jpg", "g.jpg", "i.jpg", "j.jpg"]
    let columns: CGFloat = 3
    let space: CGFloat = 1

    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.backgroundColor = .white
        
        collectionView.register(CustomCollectionCell.self, forCellWithReuseIdentifier: CustomCollectionCell.identifier)
    }

    //셀 개수
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    //셀 등록
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCollectionCell.identifier, for: indexPath) as! CustomCollectionCell
        cell.imageView.image = UIImage(named: images[indexPath.row])
        return cell
    }

    //셀 크기
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (collectionView.frame.width / columns) - (space * (columns - 1))
        return CGSize(width: width, height: width)
    }

    //위아래 간격
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return space
    }

    //좌우 간격
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return space
    }
}

전체 코드

import SnapKit
import UIKit

class CustomCollectionCell: UICollectionViewCell{
    static let identifier = "CustomCollectionCell"
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

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

    let imageView: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()

    func setupView(){
        backgroundColor = .systemGroupedBackground

        addSubview(imageView)
        
        imageView.snp.makeConstraints {
            $0.top.bottom.left.right.equalToSuperview()
        }
    }
}

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    let images = ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg", "g.jpg", "g.jpg", "i.jpg", "j.jpg"]

    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = .white
        
        self.collectionView!.register(CustomCollectionCell.self, forCellWithReuseIdentifier: CustomCollectionCell.identifier)
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCollectionCell.identifier, for: indexPath) as! CustomCollectionCell

        cell.imageView.image = UIImage(named: images[indexPath.row])
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.width / 3 - 1
        return CGSize(width: width, height: width)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }
}

참고사이트

https://abc1211.tistory.com/462

profile
👩‍💻

0개의 댓글