Notice
Recent Posts
Recent Comments
Link
大器晩成
Table View Controller - 2탄 (실전편) 본문
이번에는 위에 화면을 구성해 보는 코드를 작성해보려고 합니다.
우선 간단하게 스토리보드로도 작성이 가능하여 구성해 보도록 하겠습니다.
스토리보드에서도 비슷한 형태로 구성할 수 있습니다.
스토리보드에서 구현할 때에는 static 셀을 사용했습니다.
[Dynamic Cell]
다이나믹 셀을 사용할 경우 아래처럼 enum과 함께 쓰면 조금 더 간편하게 코드를 작성할 수 있습니다.
또한 두번째 섹션은 커스텀셀을 만들어야 해서 현재는 제외했습니다.
import UIKit
class TableViewController: UITableViewController {
enum Concentrated: CaseIterable {
case first
case second
case third
var contents: [String] {
switch self {
case .first:
return ["방해금지 모드", "개인 시간", "수면", "업무"]
case .second:
return ["모든 기기에서 공유"]
case .third:
return ["집중 모드 상태"]
}
}
var numberOfRowInSections: Int {
return contents.count
}
var image: [String] {
switch self {
case .first:
return ["moon.fill", "person.fill", "bed.double.fill", "person.crop.rectangle.fill"]
default:
return []
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return Concentrated.allCases.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionContents = Concentrated.allCases[section].contents
print("섹션 \(section) - rows: \(sectionContents.count), contents: \(sectionContents)")
return sectionContents.count
}
// MARK: - 셀 설정
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = Concentrated.allCases[indexPath.section]
// 섹션별로 셀을 다르게 설정
switch indexPath.section {
case 0:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell") else {
return UITableViewCell()
}
cell.textLabel?.text = section.contents[indexPath.row]
cell.imageView?.image = UIImage(systemName: section.image[indexPath.row])
cell.accessoryType = .disclosureIndicator
if indexPath.row == 0 {
cell.detailTextLabel?.text = ""
} else {
cell.detailTextLabel?.text = "설정"
}
return cell
case 1:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell") else {
return UITableViewCell()
}
cell.accessoryType = .disclosureIndicator
cell.detailTextLabel?.text = ""
cell.textLabel?.text = section.contents[indexPath.row]
return cell
case 2:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell") else {
return UITableViewCell()
}
cell.accessoryType = .disclosureIndicator
cell.detailTextLabel?.text = "켬"
cell.textLabel?.text = section.contents[indexPath.row]
return cell
default:
return UITableViewCell()
}
}
}
728x90
'iOS > UiKit' 카테고리의 다른 글
TableViewController - 셀의 갱신과 삭제 (0) | 2025.01.05 |
---|---|
UIStackView (0) | 2025.01.05 |
TableViewController - Dynamic , Static (0) | 2025.01.05 |
Auto Layout (0) | 2025.01.02 |
View Controller 생명주기(상태변화) (0) | 2025.01.01 |