【发布时间】:2020-09-15 10:04:20
【问题描述】:
我有这个结构的一个实例:
class AlimentObjectTronque {
var aRetinol : Float = 0
var aBetacarotene : Float = 0
var vitamineC : Float = 0
var vitamineB1 : Float = 0
var calcium : Float = 0
var omega3 : Float = 0
init(aRetinol: Float, aBetacarotene: Float, vitamineC: Float, vitamineB1: Float, calcium: Float, omega3: Float) {
self.aRetinol = aRetinol
self.aBetacarotene = aBetacarotene
self.vitamineC = vitamineC
self.vitamineB1 = vitamineB1
self.calcium = calcium
self.omega3 = omega3
}
convenience init() {
self.init(aRetinol: 0, aBetacarotene: 0, vitamineC: 0, vitamineB1: 0, calcium: 0, omega3: 0)
}
}
我需要在 tableView 的每一行中放入该结构实例的属性。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return // ????
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "CellFind", for: indexPath) as? AlimentToAddCell else {
return UITableViewCell() }
// ????
return cell
}
我需要知道如何在 tableview 的每一行中放入实例的属性。
【问题讨论】:
-
numberOfRowsInSection:返回 6,因为每个属性为 1。在cellForRowAt上,做一个switch indexPath.row {},根据它,把cell.textLabel.text设置成"\(myStruct.aRetinol)"或者对应的一个。 -
所有这一切都是
class而不是struct。它可以是一个结构体,并为您保存所有初始化代码(它会自动为您生成)。最后,你需要的只是这些对象的某种列表(数组、集合等)(刚刚意识到你说的是“属性”——仍然是一个有效的建议),以驱动你的 tableview。
标签: swift uitableview struct