Created
April 20, 2016 00:18
-
-
Save mironal/d640c57e06ce2f644137e8dc182e1256 to your computer and use it in GitHub Desktop.
UITableView の Section を Swift の enum を使っていい感じに記述する方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import XCPlayground | |
class ViewController: UITableViewController { | |
enum Section: Int { | |
case Animals = 0 | |
case Foods | |
} | |
let animals = ["Dog", "Cat"] | |
let foods = ["Apple", "Banana"] | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: String(UITableViewCell)) | |
} | |
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { | |
return 2 | |
} | |
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
switch Section(rawValue: section) { | |
case .Some(.Animals): | |
return animals.count | |
case .Some(.Foods): | |
return foods.count | |
case .None: | |
return 0 | |
} | |
} | |
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { | |
// いきなり switch case せずに guard を使って早期リターンする場合の書き方 | |
// 以降の処理が複雑になる場合はネストが深くならないのでこっちのほうがいいかも | |
guard let s = Section(rawValue: indexPath.section) else { | |
// クラッシュする | |
return tableView.dequeueReusableCellWithIdentifier("Undefined Section", forIndexPath: indexPath) | |
} | |
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(String(UITableViewCell), forIndexPath: indexPath) | |
switch s { | |
case .Animals: | |
cell.textLabel?.text = animals[indexPath.row] | |
case .Foods: | |
cell.textLabel?.text = foods[indexPath.row] | |
} | |
return cell | |
} | |
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { | |
switch Section(rawValue: section) { | |
case .Some(.Animals): | |
return "動物たち" | |
case .Some(.Foods): | |
return "食べ物たち" | |
case .None: | |
return "Undefined" | |
} | |
} | |
} | |
let vc = ViewController(style: .Grouped) | |
XCPlaygroundPage.currentPage.liveView = vc.view |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment