[英]Most efficient way of creating a table select view, with headings in swift & IOS
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.