はじめに
セクションが分かれたTableViewを作成する時、
セクションのタイトルを返す titleForHeaderInSection
セクションの数を返す numberOfSections
等を使って実装します。
一方でセルの中身は、cellForRowAt
セルの数はnumberOfRowsInSection
を1セクションのときと同じように実装しますが、複数セクションになると「1セクション目のときはセル5個、2セクション目のときはセル10個」、「1セクション目のときはセルの中身はhoge、2セクション目のときはセルの中身はfuga」といった分岐が必要になります。
そのまま書くならこうです。
ifelseで分岐
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 { // 1セクション目のとき
return animalItems.count
} else if section == 1 { // 2セクション目のとき
return foodItems.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
if indexPath.section == 0 { // 1セクション目のとき
cell.textLabel?.text = "\(animalItems[indexPath.row])"
} else if indexPath.section == 1 { // 2セクション目のとき
cell.textLabel?.text = "\(foodItems[indexPath.row])"
}
return cell
}
TableViewのセクション数が今回のように2個程度であれば問題ないですが、これが3,4,5・・・個のように増えていくとif elseの分岐が続いて可読性が低くなります。
この可読性の劣化を防ぐため、enum,switchを使ってセクション分岐をする方法をご紹介します。
step.1 セクション用のenumを定義
タイトルの通りセクション用のenumを定義します。
セクション用のenumを定義
fileprivate enum Section: Int {
case animal
case food
// これがセクション数になる
static var count: Int { return Section.food.rawValue + 1 }
}
step.2 enumを使って分岐
step.1で定義したenumを使って、セクションの分岐を行います。
enumを使ってnumberOfRowsInSectionを返す
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = Section(rawValue: section) else { return 0 }
switch section {
case .animal:
return 5
case .food:
return 10
}
}
enumを使ってcellForRowAtを返す
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let section = Section(rawValue: section) else { return UITableViewCell() }
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
switch section {
case .animal:
cell.textLabel?.text = "\(animalItems[indexPath.row])"
case .food:
cell.textLabel?.text = "\(foodItems[indexPath.row])"
}
return cell
}
セクション数も返せます(おまけ)
func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
見比べるとどうでしょうか?
if elseで分岐を行った場合に比べ、何を表示するセクションなのかが分かる状態で分岐されるため、可読性が良くなりますね!