【问题标题】:How to show item in tableView of array which is inside another array in swift?如何在 swift 中另一个数组内的数组的 tableView 中显示项目?
【发布时间】:2020-11-02 05:09:23
【问题描述】:

这是我创建的模型:

struct Friends: Codable{
var name:String
var position:String
var details:[Detail]
}
struct Detail: Codable{
var detail:String
}

我想在表格视图中详细说明。我该怎么做?

var data = [Friends]()

TableView 是:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let data = data[indexPath.row]
    let dataDetail = data.dataDetail[indexPath.row]
    cell.textLabel?.text = "\(dataDetail)"
    return cell
}

【问题讨论】:

  • 您的 Friends 结构中没有 dataDetail 属性,如果您想要的内容是 details 属性的内容,请在 textLabel 中解释您期望的输出
  • 问题的标题令人困惑,而描述不充分。请更新两者。您想在用户点击Friend cell 时打开Detail 单元格吗?

标签: arrays json swift uitableview struct


【解决方案1】:
 plz try this code
  
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
     let dta = data[indexPath.row]
         cell.textLabel?.text = dta.details[indexPath.row].detail
    return cell
}

【讨论】:

    【解决方案2】:

    为了能够显示details 数组中的所有值,您可以将map Detail 实例显示为它们的detail 值,并将join 字符串数组显示为单个逗号分隔的字符串

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let item = data[indexPath.row]        
        cell.textLabel?.text = item.details.map{$0.datail}.joined(separator: ", ")
        return cell
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-14
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2017-03-12
      • 1970-01-01
      • 2019-07-14
      • 2020-01-13
      相关资源
      最近更新 更多