학습 목표
TableView
, CollectionView
에서 Cell 등록할 때를 비롯하여
Cell 이름을 알아야 할 때, identifier를 어떻게 작성해야 휴먼에러를 방지할 지 알아보기
학습 내용
첫 번째 방법: “Cell이름”으로 관리하기
결론부터 말하면 제일 안 좋은 방법이다.
final class IssueTableViewCell: UITableViewCell { }
final class IssueListViewController: UIViewController {
private let issueTableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
issueTableView.register(
"IssueTableViewCell",
forCellReuseIdentifier: "IssueTableViewCell"
)
}
}
- 혹시 모르는 오탈자가 발생 가능성이 있음
- 셀 이름이 바뀌면 Xcode - Refactor - Rename도 못 씀
- 즉, 하나하나 직접 바꿔줘야 하는 문제가 발생하게 됨
두 번째 방법: static let identifier 상수로 관리하기
확실히 1번보다 좋은 방법이긴 한듯
최고는 아님
final class IssueTableViewCell: UITableViewCell {
static let identifier = "IssueTableViewCell"
}
final class IssueListViewController: UIViewController {
private let issueTableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
issueTableView.register(
IssueTableViewCell.identifier,
forCellReuseIdentifier: IssueTableViewCell.identifier
)
}
}
이제부터 장단점을 작성하겠다.
장점
IssueTableViewCell.identifier
로 관리하고 있으므로 셀 등록하는 곳에서 문자열에 대한 휴먼 에러를 방지할 수 있다.- 셀 이름이 바뀌면 해당 상수의 문자열만 바꾸면 된다.
단점
- 결국,
IssueTableViewCell.identifier
의 문자열을 잘못 적으면 모든 identifier가 잘못될 수 있음 - 셀의 이름이 바뀌면 상수를 바꿔줘야 하는 것 자체가 문제 (여기서 또 잘못 적을 수도 있음)
세 번째 방법: String(describing:) 사용
final class IssueTableViewCell: UITableViewCell {
static var identifier: String { String(describing: self) }
}
final class IssueListViewController: UIViewController {
private let issueTableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
issueTableView.register(
IssueTableViewCell.identifier,
forCellReuseIdentifier: IssueTableViewCell.identifier
)
}
}
- 연산 프로퍼티로 두어서 static이므로 컴파일 될 때 동작하며
self, 즉 스스로 클래스 이름에 대한 문자열 리터럴을 만든다. - 휴먼 에러를 완전히 방지할 수 있음
배운 점
- 셀 Identifier 적용에 대한 3가지 방법을 살펴봄
- String(describing: self)으로 등록하는게 제일 휴먼에러 방지하기 좋다고 생각함
참조 링크
'📱 iOS > UIKit' 카테고리의 다른 글
[UIKit] iOS 15.0 이상에서 UIButton 안에 있는 이미지 사이즈 조절하기 (3) | 2024.11.15 |
---|---|
[UIKit] 런타임 시점에 Constraint를 조절하여 애니메이션 구현하기 (2) | 2024.11.14 |
[UIKit] TableView에서 무한 스크롤 페이지네이션 처리 (2) | 2024.10.04 |
[UIView] frame & bounds (3) (0) | 2024.09.03 |
[UIView] frame & bounds (2) (10) | 2024.09.02 |