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
}
}'Swift > UITableView' 카테고리의 다른 글
| [SWIFT]UITableView 좌 - 우 스와이프 버튼 추가 (0) | 2023.07.19 |
|---|---|
| [SWIFT]UITableView Cell Drag 이동 하기 (0) | 2023.07.19 |
| [SWIFT]UITableViewCell Extention IndexPath 구하기 (0) | 2023.04.26 |