CellAdapter 를 구현해서 Cell register 시 코드 단순화 하기 위해서 만들었음.
// Cell register 등록 코드 단순화
[변경전]
collectionView.register(LineupGridCell.nib(), forCellWithReuseIdentifier: LineupGridCell.identifier)
[변경후]
collectionView.register(LineupGridCell.self)
// Cell 처리시 코드 단순화
[변경전]
if let cell = collectionView.dequeueReusableCell(withIdentifier: "TypeOptionCell",
for: indexPath) as? TypeOptionCell {
[변경후]
let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as TypeOptionCell
Extension 추가
protocol CellAdapter: class {
static var identifier: String { get }
static func nib() -> UINib
}
extension CellAdapter where Self: UIView {
static var identifier: String {
return String(describing: Self.self)
}
static func nib() -> UINib {
return UINib(nibName: self.identifier, bundle: nil)
}
}
extension UICollectionView {
func register<T: UICollectionViewCell>(_: T.Type) where T: CellAdapter {
// let Nib = UINib(nibName: T.nibName, bundle: nil)
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
}
}'Swift > UICollectionView' 카테고리의 다른 글
| [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 |
| [SWIFT]register / dequeueReusableCell 편하게 사용하기 (0) | 2023.04.26 |