Swift/UICollectionView

[SWIFT]UICollectionView register 단순화 하기

삽질중 2023. 6. 15. 09:02

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
    }
}