티스토리 뷰

iOS

[iOS] CollectionView

SiO2whocode 2021. 2. 12. 14:25
728x90

1. 스토리보드에서 Object의 CollectionView 배치, CollectionViewCell 배치, cell 내부에 UI컴포넌트 배치

 

 

2. 셀 클래스 선언 (커스텀 셀)

 

class MyCell: UICollectionViewCell{
    @IBOutlet weak var Label : UILabel!
}

ViewController랑 같은 파일에 선언해도 되고 따로 파일 만들어서 선언해도 된다. (후자 추천)

선언 후 스토리보드 CollectionViewCell의 identity inspector에서 class명 입력해서 연결

 

 

3. ViewController에서 UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout 프로토콜 채택

 

3-1. UICollectionViewDataSource가 요구하는 함수 구현 (*필수)

 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 셀 개수
}

 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? MyCell else {
    	return UICollectionViewCell()
    }
    //셀에 데이터 삽입
    return cell
}

스토리보드에서 cell의 identifier 설정

 

3-2. UICollectionViewDelegate가 요구하는 함수 구현

 

func collectionView(_ collectionView: UICollectionView,
                        didSelectItemAt indexPath: IndexPath) {
    //셀 선택시 실행되는 부분
}

 

여기까진 table view와 매우 유사하다. 사실 이름빼고 똑같음.

table view에선 indexPath.row였고 collection view에선 indexPath.item으로 접근한다.

 

3-3. UICollectionViewDelegateFlowLayout가 요구하는(?) 함수

collection view의 셀 레이아웃을 동적으로 조절할 수 있게 하는 프로토콜이다.

셀 사이즈, 여백, 셀 간 간격 등을 조정하는 함수들을 구현해서 조정할 수 있다.

 

func collectionView(_ collectionView: UICollectionView,
                          layout collectionViewLayout: UICollectionViewLayout,
                          sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 셀 가로 사이즈, height: 셀 세로 사이즈)
}

 

셀의 가로 세로 사이즈 설정

 

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

 

셀 간 열 간격

 

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

 

셀 간 행 간격

 

func collectionView(_ collectionView: UICollectionView,
                         layout collectionViewLayout: UICollectionViewLayout,
                         insetForSectionAt section: Int) -> UIEdgeInsets {
        let inset = UIEdgeInsets(top: 1, left: 1.5, bottom: 1, right: 1.5)
        return inset
}

collection view의 여백 설정

 

4. 스토리보드에서 CollectionView를 ViewController의 dataSource, delegate와 연결

 

 

 

 

728x90
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함