Created
December 16, 2018 04:01
-
-
Save churabou/35eb181d48e1b29217700f9e89268d66 to your computer and use it in GitHub Desktop.
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
// | |
// ViewController.swift | |
// TableViewExample | |
// | |
// Created by churabou on 2018/11/08. | |
// Copyright © 2018 churabou. All rights reserved. | |
// | |
import UIKit | |
struct Section { | |
var title: String | |
var items: [String] | |
} | |
extension Section { | |
static func 都道府県() -> [Section] { | |
return [ | |
Section(title: "北海道地方", items: ["北海道"]), | |
Section(title: "東北地方", items: ["青森県", "岩手県", "宮城県", "秋田県", "山形県", "福島県"]), | |
Section(title: "関東地方", items: ["茨城県", "栃木県", "群馬県", "埼玉県", "千葉県", "東京都", "神奈川県"]), | |
Section(title: "中部地方", items: ["新潟県", "富山県", "石川県", "福井県", "岐阜県", "長野県", "山梨県", "静岡県", "愛知県"]), | |
Section(title: "近畿地方", items: ["大阪府" , "京都府", "兵庫県", "奈良県", "三重県", "滋賀県", "和歌山県"]), | |
Section(title: "中国地方", items: ["鳥取県", "島根県", "岡山県", "広島県", "山口県"]), | |
Section(title: "四国地方", items: ["徳島県", "香川県", "愛媛県", "高知県"]), | |
Section(title: "九州地方", items: ["福岡県", "佐賀県", "長崎県", "大分県", "熊本県", "宮崎県", "鹿児島県", "沖縄県"]), | |
] | |
} | |
} | |
class ViewController: UIViewController { | |
private var tableView = UITableView() | |
private var sections = Section.都道府県() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
tableView.frame = view.bounds | |
tableView.dataSource = self | |
tableView.delegate = self | |
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") | |
view.addSubview(tableView) | |
} | |
} | |
extension ViewController: UITableViewDataSource { | |
func numberOfSections(in tableView: UITableView) -> Int { | |
return sections.count | |
} | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return sections[section].items.count | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) | |
cell.textLabel?.text = sections[indexPath.section].items[indexPath.row] | |
return cell | |
} | |
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { | |
return sections[section].title | |
} | |
} | |
extension ViewController: UITableViewDelegate { | |
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { | |
print(sections[indexPath.section].items[indexPath.row]) | |
} | |
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { | |
return 50 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment