본문은 야곰 아카데미 커리어 스타터 캠프를 통해 학습한 내용을 회고한 글입니다.
프로토콜로 id 지정하기
다음과 같은 코드로 프로토콜을 통해 identifier를 지정할 수 있다:
import UIKit
protocol IdentifierType {
static var identifier: String { get }
}
extension IdentifierType {
static var identifier: String {
return String(describing: self)
}
}
extension UIViewController: IdentifierType { }
extension CustomTableViewCell: IdentifierType { }
IdentifierType이라는 프로토콜을 생성하고, extension을 통해서 스스로의 이름과 같은 identifier를 내뱉을 수 있다. UIViewController와 CustomTableViewCell에게 적용해줬다.
그러면 스토리보드에서 다음과 같이 ID를 정해주지 않아도 동작할 수 있다:
사용은 다음과 같이 한다:
@IBAction private func touchUpInsideItemButton(_ sender: UIButton) {
guard let itemListViewController: ItemListViewController = self.storyboard?.instantiateViewController(withIdentifier: ItemListViewController.identifier) as? ItemListViewController else { return }
navigationController?.pushViewController(itemListViewController, animated: true)
}
withIdentifier 뒤에 하드코딩을 하는 대신에 ItemListViewController.identifier를 넣어주면 하드코딩을 하지 않을 수 있다.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: CustomTableViewCell.identifier, for: indexPath) as? CustomTableViewCell else { return CustomTableViewCell() }
let exhibitItem: ExhibitItem = exhibitItems[indexPath.row]
cell.configureContent(exhibitItem: exhibitItem)
return cell
}
CustomTableViewCell의 경우도 마찬가지로 CustomTableViewCell.identifier라고 코드를 작성해주면 된다.
'YAGOM CAREER STARTER' 카테고리의 다른 글
[TIL] 20230309: Sync/Async/Blocking/Non-Blocking (0) | 2023.03.09 |
---|---|
[TIL] 20230307: 동기/비동기/직렬/동시성, DispatchQueue (0) | 2023.03.07 |
[TIL] 20230302: 함수배치순서, format specifier (0) | 2023.03.03 |
[TIL] 20230228: Convention, weak-strong (0) | 2023.03.01 |
[TIL] 20230227: instantiateViewController (0) | 2023.02.28 |