【问题标题】:How to populate data to a UITableView from Array which is in a model Array?如何将数据从模型数组中的数组填充到 UITableView?
【发布时间】:2018-08-23 05:59:45
【问题描述】:

我有一个模型类数组,这个模型类有一个数组。我想从数组填充表格视图。它向我显示错误

这是我的模型类

class DataModel {

    var name:[String]

    init(name:[String]) {
        self.name = name
    }
} 

这是我的模型对象:

class Data {
    static var product = [DataModel]()
}

这是我将数据附加到对象的函数:

class Function {

    static func read(compleationHandler:@escaping ()->()) {

        var model = ["nsu","iUB","UIU"]
        DispatchQueue.global(qos: .userInteractive).async {
            if Data.product.count == 0 {
                Data.product.append(DataModel(name: model))
            }
            DispatchQueue.main.async {
                compleationHandler()
            }
        }
    }
}

这是我的 tableView Cell 方法:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = myTableView.dequeueReusableCell(withIdentifier: "myCell") as! myCell

        cell.textLabel?.text = Data.product[indexPath.row].name[indexPath.count]

        return cell
    }

这是我的 ViewDidLoad :

myTableView.delegate = self
        myTableView.dataSource = self
        Function.read { [weak self] in
            print(Data.product.count)
            self?.myTableView.reloadData()
        }

    }

【问题讨论】:

  • 错误是什么?它在哪里显示?
  • “线程 1:致命错误:索引超出范围”
  • 我想从这个数组中填充属于模型“cell.textLabel?.text = Data.product[indexPath.row].name[indexPath.row]”的数据
  • 这可能是因为您在 cellForRowAt 中使用了错误的索引。 cell.textLabel?.text = Data.product[indexPath.section].name[indexPath.row] 但我不能确定,除非我看到你的 numberOfSections 和 numberOfRows 代表。

标签: ios swift uitableview


【解决方案1】:

问题可能在于您的代表的设置方式。这就是我觉得你正在努力实现的目标。

func numberOfSections(in tableView: UITableView) -> Int {
    return Data.product.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return Data.product[section].name.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = myTableView.dequeueReusableCell(withIdentifier: "myCell") as! myCell

    cell.textLabel?.text = Data.product[indexPath.section].name[indexPath.row]

    return cell
}

【讨论】:

  • 谢谢它的工作,但如果我在一个部分填充它怎么可能?
  • 您必须将所有名称映射到一维数组并将其用作数据源。在 numberOfSections 中也返回 1。你可以参考这个来了解如何扁平化多维数组 - stackoverflow.com/questions/24465281/…
猜你喜欢
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
相关资源
最近更新 更多