UICollectionView 를 매우 흔하게 사용하기 때문에 코드를 하나라도 축약해서 편하게 사용하기위해 extension을 추가해서 사용한다.
여러개의 Cell을 사용하다보면 쉽게 사용하기 위해 Adapter를 사용 한다.
// MARK: CellTypeAdapter - CollectionView/TableView Cell Type Adapter
protocol CellTypeAdapter {
var identifier: String { get }
func nib() -> UINib
}
extension CellTypeAdapter {
var identifier: String {
return String(describing: Self.self)
}
func nib() -> UINib {
return UINib(nibName: self.identifier, bundle: nil)
}
}
extension UICollectionView {
/// 별도의 Cell UI를 사용할 경우 register 해주는 부분을 줄여준다.
func register<T: UICollectionViewCell>(_: T.Type) where T: CellAdapter {
register(T.nib(), forCellWithReuseIdentifier: T.identifier)
}
/// 재사용 가능한 셀을 대기열에서 빼기
func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T where T: CellAdapter {
guard let cell = dequeueReusableCell(withReuseIdentifier: T.identifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.identifier)")
}
return cell
}
}
사용방법
/// Cell UI를 xib로 구성할 경우 register 사용
@IBOutlet weak var cellectionView: UICollectionView {
didSet {
//기본적인 사용 예시
collectionView.register(UserContentCell.self, forCellWithReuseIdentifier: "UserContentCell")
//CellAdapter 사용 예시
collectionView.register(UserContentCell.self)
}
}
/// UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//기본적인 사용 예시
let cell = collectionView.dequeueReusableCell(withReuseIdentitifier: "UserContentCell", for: indexPath) as? UserContentCell
//Extention / CellAdapter 사용 예시
let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as UserContentCell
return cell
}'Swift > UICollectionView' 카테고리의 다른 글
| [SWIFT]UICollectionView register 단순화 하기 (0) | 2023.06.15 |
|---|---|
| [SWIFT]UICollectionViewCell Extention IndexPath 구하기 (0) | 2023.04.26 |
| [SWIFT]UICellectionView RefreshControl 추가하기 (0) | 2023.04.26 |
| [SWIFT]현재 화면 중앙에 보여지고 있는 Cell의 IndexPath가져오기 (0) | 2023.04.26 |
| [SWIFT]UICollectionView 백그라운드 Empty Message 추가 (0) | 2023.04.26 |