どうも、はじめです。
今回はSectionやCellの指定にSwitchとEnumを使ってみようと思います。
SwitchとEnumを使用するメリットとしてはEnumのすべてのCaseを網羅していないとエラーになってしまうため
漏れが無くなるところにあります。
複数人で開発をしている時などにとても便利ですね。
今回は例としてCellのTitleをEnumのCase毎に変更してみようと思います。
実行結果は以下のようになります。
では早速。
・Xcode 8.3.3
・Swift 3
まずは使用するEnumを用意します。
enum EnumCells: Int { case firstCell = 0 case secondCell case thirdCell }
上記のままだとCell数を返す時のcountが返せません。
調べてみてもあまり気持ちい書き方が見当たらずもやもやするところもありますが、
以下を追記することでcountを返すことができます。
static var count: Int { return EnumCells.thirdCell.rawValue + 1 }
通常通りTableの用意をしておきます。
1. StoryBoard上でTableViewを追加し、delegateとdatasourceを設定
2. ViewControllerにUITableViewDelegateとUITableViewDataSourceを継承させる
3. UITableViewDataSourceの実装必須メソッドを追記
さて、ようやく本題に来ました。
まずはCell数を返します。
Enumの用意の際にEnumのCaseの数を取得できるようにしていたので
以下を記述するだけでCaseの数を取得することができます。
EnumCells.count
次にEnumのCase毎にCellのTitleを変更させます。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var titleText = "" let enumCell = EnumCells(rawValue: indexPath.row) switch (enumCell)! { case .firstCell: titleText = "FirstCell" case .secondCell: titleText = "SecondCell" case .thirdCell: titleText = "ThirdCell" } let cell = UITableViewCell() cell.textLabel?.text = titleText return cell }
ここで使用するCaseにEnumのすべてのCaseが使用されていなければエラーとなります。
また、SwitchにEnumを使用することでDefaultを記述する必要がなくなります。
こうすることによって網羅していなければいけない箇所でも漏れがなくなります。
以上で完成です。
完成後のソース全量を表示しておきます。
import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { enum EnumCells: Int { case firstCell = 0 case secondCell case thirdCell static var count: Int { return EnumCells.thirdCell.rawValue + 1 } } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return EnumCells.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var titleText = "" let enumCell = EnumCells(rawValue: indexPath.row) switch (enumCell)! { case .firstCell: titleText = "FirstCell" case .secondCell: titleText = "SecondCell" case .thirdCell: titleText = "ThirdCell" } let cell = UITableViewCell() cell.textLabel?.text = titleText return cell } }
SwitchとEnumの組み合わせは他にもいろいろな場所で利用できると思います。
今回はCellに使用しましたが、TableやCollectionだけでもSectionに使用したり
HeightやLayoutの変更に使用したりとかなり便利だと思います。
最後まで見ていただきありがとうございました。