ios - 将多个数据数组显示到单个 TableView 部分的有效方法

标签 ios swift

我有一个数据模型如下:

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/

相关文章:

ios - 无法取消隐藏按钮,除了 ViewDidLayoutSubviews()

ios - 以编程方式将图片裁剪为正方形的解决方案出现问题

ios - NSJSON 序列化 - "Unexpected end of file during string parse"

ios - AVPlayerLayer 没有出现几秒钟,但声音完美

ios - 禁用 Firebase Analytics for iOS 调试版本

css - 我们如何在 ios 9 的 uiwebview 中禁用放大镜 - Swift

swift - 创建基于ERD的类架构

ios - 通过动画 : iOS 向 UITableViewCell 添加单选按钮

iphone - 如何使用 Objective C 匹配两个随机数,然后在 xcode 界面生成器中打印匹配

ios - (null) 在使用 NSDateFormatter 之后