LoginSignup
30
31

More than 5 years have passed since last update.

enumを使ってTableViewを見やすく書けないか

Last updated at Posted at 2015-04-28

当たり前だけど、tableviewを記述するときにsection(row)にマジックナンバーを使うとカオスになることが多々ある。objective-cのときはNSENUMつかってやってたけど、swiftだとどうなるのかなと思い書いてみた

やったこと概要

  1. enumにSection情報をまとめる
  2. indexPathから列挙子を取得 #rawから列挙子を取得
  3. enumから必要な情報をとってきてdatasourceに設定

Sectionの情報まとまったので、確認しやすくなった気がする。
もっとエレガントな書き方知りたい

enumにSection情報をまとめる

    private enum SectionType:Int {
        case Fruit = 0
        case Vegitable
        case Max

        func configure() -> (sectionTitle:String, cellIdentifier:String) {
            switch self {
            case .Fruit:
                return ("fruit section", "FruitCell")
            case .Vegitable:
                return ("vegitable section", "VegitableCell")
            case .Max:
                return ("", "")
            }
        }
    }

enumから必要な情報をとってきてdatasourceに設定

cellの設定

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //rawから列挙子を取得
        let section = SectionType(rawValue: indexPath.section)!

        //sectionに応じたidentifierを取得
        let (_, identifier) = section.configure()
        var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as! UITableViewCell

        //section毎にcellを処理
        switch section {
        case .Fruit:
            return self.configureCellForFruitCell(cell as! FruitCell, indexPath: indexPath)
        case .Vegitable:
            return self.configureCellForVegitableCell(cell as! VegitableCell, indexPath: indexPath)
        case .Max:
            return UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Default")
        }

    }

タイトルの設定

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        //configureから必要なtitleを取り出して利用
        let (title, _) = SectionType(rawValue: section)!.configure()
        return title
    }

section/rowの数を設定

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return SectionType.Max.rawValue
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch SectionType(rawValue: section)! {
        case .Fruit:
            return self.fruitsData.count
        case .Vegitable:
            return self.vegitablesData.count
        default:
            println("undefined section")
            return 0
        }
    }
30
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
31