Populate Table Section and Rows from Array of Dict

2019-07-23 15:04发布

问题:

I have a table that I'm trying to populate from a class that stores the model data. Firstly, my data is stored as an array of dictionaries as follows:

var pupilSubjects = ["Tom":["English", "Geography", "History"], "Dick":["English", "Geography", "Physical Education", "Biology"], "Harry": ["English", "Geography", "Physical Education", "Biology"]]

In my TableViewController in viewDidLoad I take the information in my array of dictionaries and add each dictionary to a class that I called TableText like so:

for dict in pupilSubjects {

        let key = dict.0
        let values = dict.1


       tableTexts.append(TableText(name: key, subject: values))
    }

my variable tableTexts is stored in my TableViewController as follows:

var tableTexts = [TableText]()

My TableText class is as follows:

import UIKit

class TableText: NSObject {

var name: String
var subject: [String]


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

  }

}

I have a custom TableViewCell which I call myTableViewCell where I set tableText data as follows:

   var tableText: TableText? {
    didSet {
        let myInputText = myTextView.text
        tableText!.subject.append(myInputText)
        //  stepNumber.text = msStep!.step

    }
}

I am struggling to implement cellForRowAtIndexPath in my TableViewController to display my section and row details that I have stored in my var tableTexts = TableText. I can get the keys from my section title like so:

let myKey = sectionTitles[indexPath.section]

but I'm unsure how to use each key to return the array of strings stored in tableTexts. Any help / pointers would be greatly appreciated.

回答1:

According your specification the relevant table view delegate / data source methods are

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  let pupil = tableTexts[section]
  return pupil.name
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
  return tableTexts.count
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  let pupil = tableTexts[section]
  return pupil.subject.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

  let pupil = tableTexts[indexPath.section]
  cell.textLabel!.text = pupil.subject[indexPath.row]
  return cell
}