-
Notifications
You must be signed in to change notification settings - Fork 0
[week08] TableView, JSON
Hemg edited this page Jul 1, 2023
·
8 revisions
- TableView를 생성할 수 있다.
- TableView의 Section과 Row의 개념을 이해하고, 원하는 정보를 Cell 에 표현할 수 있다.
예제 코드
- Hemg
enum FoodMenu: String, CaseIterable {
case American
case Chinese
case Korean
case Japanese
}
struct Foods {
let name: String
let price: Int
}
class FoodViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "메뉴판"
tableView.dataSource = self
}
let foodType = FoodMenu.allCases
let menu: [FoodMenu: [Foods]] = [
.American: [
Foods(name: "징버거버", price: 9000),
Foods(name: "고르곤", price: 35000),
Foods(name: "아아", price: 2000),
],
.Chinese: [
Foods(name: "꽃핀가지", price: 40000),
Foods(name: "짜장면", price: 9000)
],
.Korean: [
Foods(name: "명륜진사갈비", price: 18900),
Foods(name: "자연별곡", price: 19900)
],
.Japanese: [
Foods(name: "타코와사비", price: 9900),
Foods(name: "간장새우", price: 10900)
]
]
}
extension FoodViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return foodType.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return foodType[section].rawValue
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let a = menu[foodType[section]] else { return 0 }
return a.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else { return UITableViewCell() }
cell.textLabel?.text = menu[foodType[indexPath.section]]?[indexPath.row].name
if let a = menu[foodType[indexPath.section]]?[indexPath.row].price {
cell.detailTextLabel?.text = String(a)
}
return cell
}
}
예제 코드
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
private let kind = ["American", "Chinese", "Korean", "Japanese"]
private let food = [["햄버거", "피자", "아메리카노"], ["탕수육"], ["비빔밥", "돼지갈비"], ["스시", "스윙스(돈까스)"]]
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "메뉴판"
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return kind.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return food[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CustomTableViewCell else { preconditionFailure("테이블 뷰 셀 가져오기 실패") }
cell.label.text = food[indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return kind[section]
}
}