I'd like to have a table view that's used to select a key,value pair. The table will be re-usable for multiple uses, but here's an example using classes and students:
11A/It
4125:John
5121:Ben
6121:Anna
4125:Gemma
10B/It
5121:Ben
6121:Anna
4125:Gemma
4512:Kevin
The class names are the headings - they will not be selectable. The students are selectable, and the table view will pass back both the key and the value, via a protocol.
What is important, is that these all remain in order, which means my first attempt doesn't really work:
var data = [String:[String:String]()
// Causes problems, because dictionaries have no order
So, I thought I could turn the dictionaries into arrays:
var data = [[String:[[String:String]]]()
This allows me to get the number of sections, but then I can't figure out how to get the number of rows:
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].first.count // Nope!
}
So, I think I'm looking for a bit of general advice on the best approach. I can see two ways around this:
I've got a feeling I might be overcomplicating things though - is there a standard accepted way to solve this one. It seems like it must be a pretty common thing to come across? Many thanks in advance!
I would create a struct that can hold your data, rather just an abstract dictionary.
For example
struct ClassData {
let title: String
let students: [Student]
}
struct Student {
id: Int
name: String
}
let tableData = [ClassData]()
func numberOfSections(in tableView: UITableView) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData[section].students.count
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.