본문으로 바로가기

[iOS] CollectionView 사용하기

category iOS 2022. 7. 4. 20:23
728x90

1. CollectionView란?

iOS에서 리스트 및 그리드 뷰를 구성하기 위한 뷰(View)

2. 스토리보드 구성

A. ViewController

UIViewController 클래스와 연결(Custom class, Storyboard ID) 시켜준다.

B. CollectionView

해당 인스턴스를 UIViewController 클래스에 추가한다.

C. CollectionViewCell

UICollectionViewCell 클래스와 연결 시켜준다.

각 요소들의 인스턴스를 UICollectionViewCell 클래스에 추가한다.

3. 소스코드 구성

A. UIViewController

뷰를 제어하기 위한 클래스

class FrameworkListViewController: UIViewController {   
    @IBOutlet weak var collectionView: UICollectionView!
    let list: [AppleFramework] = AppleFramework.list
    
    // Data, Presentation, Layout
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.dataSource = self
        collectionView.delegate = self
        // 여백
        collectionView.contentInset = UIEdgeInsets(top: 20, left: 16, bottom: 0, right: 16)
    }
}

UICollectionView의 구성요소

  • dataSource: 리스트를 구성하는 데이터 제어. UICollectionViewDataSource
extension FrameworkListViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return list.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FrameworkCell", for: indexPath) as? FrameworkCell else {
            return UICollectionViewCell()
        }
        let framework = list[indexPath.item]
        cell.configure(framework)
        return cell
    }
}
  • delegate: 각 레이아웃의 크기 제어. UICollectionViewDelegateFlowLayout
extension FrameworkListViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let interItemSpacing: CGFloat = 10
        let padding: CGFloat = 16

        let width = (collectionView.bounds.width - interItemSpacing * 2 - padding * 2) / 3
        let height = width * 1.5
        return CGSize(width: width, height: height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
}

// 항목 선택
extension FrameworkListViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let framework = list[indexPath.item]
        print(">>> selected: \(framework.name)")
    }
}

B. UICollectionViewCell

리스트의 개별 항목을 구성하기 위한 클래스

각 항목을 불러올 때마다 awakeFromNib함수가 호출된다.

구성요소들의 데이터를 갱신시켜준다.

class FrameworkCell: UICollectionViewCell {    
    @IBOutlet weak var thumbnailImageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        nameLabel.numberOfLines = 1
        nameLabel.adjustsFontSizeToFitWidth = true 
    }
    
    func configure(_ framework: AppleFramework) {
        thumbnailImageView.image = UIImage(named: framework.imageName)
        nameLabel.text = framework.name
    }
}
728x90