Swift/UITableView

[SWIFT]UITableView register 단순화 하기

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

UICollectionView 거의 동일한 Extention으로 코드 단순화 할 수 있다.

// Cell register 등록 코드 단순화
[변경전]
tableView.register(LineupGridCell.nib(), forCellWithReuseIdentifier: LineupGridCell.identifier)
[변경후]
tableView.register(LineupGridCell.self)

// Cell 처리시 코드 단순화
[변경전]
if let cell = tableView.dequeueReusableCell(withIdentifier: "TypeOptionCell",
 for: indexPath) as? TypeOptionCell {
    
[변경후]  
let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as TypeOptionCell

 

Extention 추가

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 UITableView {
    
    func register<T: UITableViewCell>(_: T.Type) where T: CellAdapter {

        self.register(T.nib(), forCellReuseIdentifier: T.identifier)
    }
    
    func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: CellAdapter {
        guard let cell = dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(T.identifier)")
        }
        return cell
    }
}