【问题标题】:Swift - Populate uitableview with dictionary of [String: [String: String]]Swift - 使用 [String: [String: String]] 的字典填充 uitableview
【发布时间】:2019-01-28 10:48:35
【问题描述】:

我是 Swift 新手,我目前正在创建一个向用户提问的日记应用。我像这样存储用户的输入:

dict = ["date": ["question1": "answer", "question2": "answer"]]

现在我需要在表格视图中将这些数据显示给用户,其中“日期”是标题,“问题 1”是描述。

我在网上看过,但答案似乎引用“indexPath.row”来将信息输入到单元格中,但由于这是一个字符串字典,我不能这样做。

感谢您的帮助!

【问题讨论】:

标签: ios swift uitableview dictionary


【解决方案1】:

您应该考虑使用能够更好地表示您的数据的对象,而不是使用字典数组。

struct Question: {
    let question: String
    let answer: String
}

struct DiaryDay {
    let date: Date // Note this is a Date object, not a String
    let questions: [Question]
}

那么你有

let diaryDays = DiaryDay(date: <date>, questions: 
    [Question(question: "question1": answer: "answer"),
     Question(question: "question2": answer: "answer")])

虽然有更多代码,但您会发现更容易看到正在发生的事情。

看起来你应该每天写一个部分……

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

然后每个问题一行…

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let diaryDay = diaryDays[section]
    return diaryDay.questions.count
}

然后配置您的单元格……

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // dequeue cell
    let diaryDay = diaryDays[indexPath.section]
    let question = diaryDay.questions[indexPath.row]    
    cell.question = question
    return cell
}

并在部分标题中显示日期...

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let diaryDay = diaryDays[section]

    return // formatted diaryDay.date
}

【讨论】:

    【解决方案2】:

    在显示您正在使用的字典类型中的数据之前,您必须做一些准备工作。还要记住字典不是订单列表,因此打印数据的顺序完全取决于系统。一种方法如下

    var data = ["date1":["q1":"A1","q2":"A2","q3":"A3"],"date2":["q1":"A1","q2":"A2","q3":"A3"]] . //This is data from your example
    var displayableData = [(title: String, qAndA: [(question: String, answer: String)])]() //this is what we will be needing
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        //convert the whole dictionary to tuple
        displayableData = data.map { ($0.key, $0.value.map{ ($0.key, $0.value)})}
    
        //here we have converted the dictionary to what we need
    }
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return displayableData.count  
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return displayableData[section].qAndA.count
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55.0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let currentQA = displayableData[indexPath.section].qAndA[indexPath.row]
        cell.textLabel?.text = "\(currentQA.question) -> \(currentQA.answer)"
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30.0
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 30.0))
        view.backgroundColor = UIColor.lightGray
        let label = UILabel(frame: CGRect(x: 10, y: 0, width: view.bounds.width - 20, height: 30.0))
        label.text = displayableData[section].title
        view.addSubview(label)
        return view
    }
    

    【讨论】:

      【解决方案3】:

      您可以尝试使用map。这里Dictionary 转换为字典数组。

      let dict = ["date": ["question1": "answer", "question2": "answer"]]
      
      if let value = dict["date"] {
          let v = value.map {
              ["question": $0.key, "answer": $0.value]
          }
      
          debugPrint(v)
      }
      

      【讨论】:

        【解决方案4】:

        您可以按原样使用字典

        你应该在使用前进行排序,记住

        let dict = ["date": ["question1": "answer", "question2": "answer"]]
        

        部分数量

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

        标题的标题

        override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            return Array(dict)[section].key
        }
        

        部分的行数

        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            let key = Array(dict)[section].key
            return dict[key]?.count ?? 0
        }
        

        所在行的单元格

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
           let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
           let key = Array(dict)[section].key
           if let questionsDict = dict[key] {
             let keyValue = Array(questionsDict)[indexPath.row]
             print("Question: \(keyValue.key), Answer: \(keyValue.value)")
           }
           return cell
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-08
          • 2017-11-22
          • 2016-10-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多