Search
⛓️

7. [No StoryBoard] collectionView

부제
카테고리
UIKit
세부 카테고리
스토리보드 없이 개발하기
Combine 카테고리
최종편집일
2022/09/20 08:15
작성중
관련된 포스팅
생성 일시
2022/07/16 14:26
태그

1 : Cell 타입 정의해주기

import UIKit class TweetCell: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .red } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
Swift
복사
Note : 사실 UIView 를 상속받아 새로운 생성자를 사용한다는 것은 사용자(개발자)가 뷰를 생성하는 방법을 직접 하겠다  라는 의미로 봐도 무방하다.

2 : UICollectionViewController 상속받기

If you create the collection view controller programmatically, it automatically creates a new unconfigured collection view object, which you can access using the collectionView  property. 컬렉션 뷰 컨트롤러 를 코드로 만들면 자동으로 collection view 객체가 생성된다. collectionView 프로퍼티로 접근이 가능하다.
If a data source or delegate is not specified, the collection view controller assigns itself to the unspecified role. 또한 자동으로 collectionView 의 delegatedatasource 에 상속받은 뷰컨트롤러를 할당한다.
//UICollectionViewController 사용 class FeedController: UICollectionViewController { // MARK: - lifeCycles override func viewDidLoad() { super.viewDidLoad() //컬렉션 뷰에 사용할 Cell 의 타입을 등록해주기 collectionView.register(TweetCell.self, forCellWithReuseIdentifier: "TweetCell") } }
Swift
복사

3 : 컬렉션 뷰 레이아웃을 사용한 컨트롤러 인스턴스 생성

let feed = FeedController(collectionViewLayout: UICollectionViewFlowLayout()) let nav1 = templateNavigationController(image: UIImage(named: "home_unselected"), rootViewController: feed)
Swift
복사

4 : 컬렉션 뷰 커스텀

데이터 연결

numberOfItemsInSection : 섹션 별 아이템 개수
cellForItemAt : 보여질 셀 생성 및 데이터 연결
extension FeedController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 5 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) return cell } }
Swift
복사

아이템 사이즈 조절 : UICollectionViewDelegateFlowLayout

sizeForItemAt : 각 아이템의 사이즈 조절
minimumInteritemSpacingForSectionAt : 아이템 열간 간격
// MARK: - UICollectionViewDelegateFlowLayout extension ProfileFilterView: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: self.frame.width / 3, height: self.frame.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } }
Swift
복사

5 : 기타 커스텀

status bar 무시하기

collectionView.contentInsetAdjustmentBehavior = .never
Swift
복사