我想要一个 UITableView 来显示以下数据:
代替:
我使用的代码如下:
// Data model class defining an Animal
class Animal {
// data members
var name: String
var type: String
// initializer
init(name: String, type: String) {
self.name = name
self.type = type
}
}
和
// View Controller
import UIKit
class AnimalsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// an array of Animal(s)
var animals: [Animal] = [Animal("Cat", "Domestic"), Animal("Dog", "Domestic"), Animal("Lion", "Wild"), Animal("Deer", "Wild"), Animal("Tiger", "Wild")];
override func viewDidLoad() {
super.viewDidLoad();
}
// returns the number of rows to be present in table
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animals.count
}
// returns each cell to be present in the table
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentfier = "animalbasic"
// uses a protype cell from storyboard
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentfier)
cell.textLabel.text = animals[indexPath.row].name
return cell
}
}
为了获得所需的输出,我需要在我的代码中更改什么?(假设数组始终按照 Animal.type 排序)
最佳答案
您需要按类型将数据分成几个部分。
class AnimalsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var animals: [Animal] = [Animal("Cat", "Domestic"), Animal("Dog", "Domestic"), Animal("Lion", "Wild"), Animal("Deer", "Wild"), Animal("Tiger", "Wild")]
var sections: [[Animal]] = []
override func viewDidLoad() {
super.viewDidLoad();
var sectionForType = [String: [Animal]]()
for animal in animals {
if sectionForType[animal.type] == nil { sectionForType[animal.type] = [] }
sectionForType[animal.type]!.append(animal)
}
sections = sectionForType.keys.sorted().map({ sectionForType[$0]! })
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section][0].type
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "animalbasic")!
cell.textLabel!.text = sections[indexPath.section][indexPath.row].name
return cell
}
}
关于ios - 如何明智地显示 UITableView 单元格类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43473828/