我有一个数据模型如下:
class Model {
var field1 = Data()
var field2 = Data()
var field3 = [Data]()
var field4 = [Data]()
}
var model = Model() // Provide data here
模型将从API中获取和解析,我使用另一个类数据作为子模型来形成模型。我需要按以下顺序将模型对象显示到单个 TableView 部分:
field1 -> field2 -> [field3] -> [field4]
我打算做的如下:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.count
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StatusCell") as! StatusCell
switch indexPath.row {
case 0:
// Do something with field1
case 1:
// Do something with field2
case 2...(2 + field3.count):
// Do something with field3
case (2 + field3.count)...(2 + field3.count + field4.count)
// Do something with field4
return cell
}
正如我的观点,它非常低效,因为每次调用 cellForRowAt 时,它都必须一次又一次地计算数组大小,但我必须检查数组以按照上面的预定义顺序显示它们。然而,这是我目前唯一的想法。
我想改进代码以获得更高的效率,可能是数据应该存储在模型中的方式(而不是数组或类似的东西......)或者如何将数据正确地填充到 TableView 中。请帮忙指出代码应该在哪里改进以及如何改进。
谢谢
最佳答案
最简单的方法是您可以使用 tableView Section,但是正如您所描述的那样,您想要在单个部分中填充所有数据字段,因此只需不要实现 titlefroHeader 委托(delegate)或在此委托(delegate)中传递空字符串即可,您可以看到tableview 像在单个部分中一样填充。
override func numberOfSections(in tableView: UITableView) -> Int {
return numberOfFields
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0
{
return [field1 count]
}
else
{
return [otherfield count]
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView .dequeueReusableCell(withIdentifier: "cell")!
if indexPath.section == 0
{
cell.textLabel?.text = field1 .object(at: indexPath.row)
}
else
{
cell.textLabel?.text = otherfield .object(at: indexPath.row)
}// assuming fileds array containing string
return cell
}//pass empty string in this delegate or dont implement it, or if you want to display the first header text the pass in other empty string
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0
return "section"
else
return ""
}
如有其他问题欢迎讨论
关于ios - 将多个数据数组显示到单个 TableView 部分的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45341915/