CollectionViewController 생성 (첫 번째 CollectionView 선언)
CollectionViewCell 생성
CollectionHeaderView생성 (두 번째 CollectionView 선언)
CollectionHeaderView.swift
// protocol 생성 - 함수 선언만
protocol CellDelegate {
func selectedCell(_ index: Int, _ data: String)
}
class CollectionHeaderView: UICollectionReusableView {
// delegate 선언
var delegate: CellDelegate?
}
extension CollectionHeaderView: UICollectionViewDelegate, UICollectionViewDataSource {
// 선택된 Cell에 대한 정보 전달
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.selectedCell(indexPath.row, testModel.itemAt(indexPath.row))
}
}
CollectionViewController.swift
// Header쪽 함수
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
headerView.delegate = self // delegate로 대리자 위임
}
// CellDelegate 채택 후 메소드 구현
extension CollectionViewController: CellDelegate {
func selectedCell(_ index: Int, _ data: String) { // data의 타입은 자유롭게 설정
let vc = UIStoryboard(name: "TestView", bundle: nil).instantiateViewController(withIdentifier: "TestViewController") as! TestViewController
vc.modalPresentationStyle = .fullScreen
vc.setData(data) // TestViewController에 정보받는 함수 sendData() 선언 해놓음
self.navigationController?.pushViewController(vc, animated: true)
}
}
github 링크 https://github.com/0inn/iOS_Study/tree/main/0innTemplate/0innTemplate/Source/CollectionView