[swift] IGListKit에서 셀의 디자인 변경하는 방법

IGListKit은 iOS 애플리케이션에서 복잡한 컬렉션 뷰 화면을 쉽게 관리할 수 있도록 도와주는 라이브러리입니다. IGListKit을 사용하면 셀의 디자인을 변경하고 커스터마이징하는 것도 간단합니다.

IGListKit 셀 디자인 변경 방법

  1. 셀 레이아웃 생성하기: IGListSectionController를 상속받는 클래스 내에서 IGListSingleSectionController를 사용하여 셀 디자인을 변경할 수 있습니다. 예를 들어, 다음과 같은 코드를 사용하여 셀의 크기와 모양을 설정할 수 있습니다.
class MyListSectionController: IGListSectionController {
    // 셀 크기 설정
    override func sizeForItem(at index: Int) -> CGSize {
        let width = collectionContext?.containerSize.width ?? 0
        let height: CGFloat = 50
        return CGSize(width: width, height: height)
    }
    
    // 셀 생성 및 바인딩
    override func cellForItem(at index: Int) -> UICollectionViewCell {
        guard let cell = collectionContext?.dequeueReusableCell(of: MyCell.self, for: self, at: index) as? MyCell else {
            fatalError()
        }
        
        // 셀에 데이터 바인딩
        let data = object(at: index)
        cell.titleLabel.text = data.title
        
        return cell
    }
}
  1. 커스텀 셀 디자인 작성하기: IGListKit에서 사용할 셀의 디자인을 설정하기 위해 UICollectionViewCell을 상속받는 커스텀 셀을 작성해야 합니다. 예를 들어, 다음과 같이 셀 내에 제목을 표시하는 MyCell 클래스를 작성할 수 있습니다.
class MyCell: UICollectionViewCell {
    let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 셀 내 요소 배치
        addSubview(titleLabel)
        // ...
        
        // 셀 내 요소 제약 조건 설정
        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
            // ...
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
  1. 셀 디자인 설정하기: IGListKit으로 데이터를 관리하는 컨트롤러에서 IGListAdapterDataSource 프로토콜을 따르는 IGListAdapterDataSource 객체를 사용하여 셀의 디자인을 설정할 수 있습니다. 예를 들어, 다음과 같이 adapter 객체를 생성하고 셀 디자인을 설정할 수 있습니다.
let adapter = IGListAdapter(updater: IGListAdapterUpdater(), viewController: self)
adapter.collectionView = collectionView
adapter.dataSource = self
// ...

extension ViewController: IGListAdapterDataSource {
    // 섹션 컨트롤러 반환
    func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
        return MyListSectionController()
    }
    
    // 객체 데이터 반환
    func objects(for listAdapter: IGListAdapter) -> [ListDiffable] {
        // ...
    }
    
    // 각 섹션의 고유 식별자 반환
    func listAdapter(_ listAdapter: IGListAdapter, identifierFor object: Any) -> NSObjectProtocol {
        // ...
    }
}

위의 예제 코드는 IGListKit을 사용하여 셀의 디자인을 변경하는 방법을 보여주고 있습니다. 이를 참고하여 IGListKit을 사용하여 iOS 애플리케이션에서 셀의 디자인을 커스터마이징할 수 있습니다.

참고 자료