如何使用swift3在我的TableView中获取部分

时间:2016-11-09 19:59:01

标签: ios uitableview swift3

我想在TableView中添加部分,

我有:

 var sections = SectionData().getSectionsFromData() // Declaration: [(key: String, value: [String])]

我的所有数据都存储在"部分"中。在密钥存储所有ABC和值中所有以26字母之一开头的项目

我无法弄清楚如何访问这些值

我的代码:

var sections = SectionData().getSectionsFromData()

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return sections.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return sections.[section].count // error 
}

2 个答案:

答案 0 :(得分:0)

我假设你的dataSource是一个像这样的元组数组:

let sections: [(key: String, value: [String])] = [("A", ["Andrew", "Anna"]), ("B", ["Barbie", "Brad"])]

然后您的numberOfRowsInSection方法应如下所示:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section].value.count
}

答案 1 :(得分:0)

Sections是[String:[String]]的字典,你试图用一个整数的section来索引它。相反,您必须按部分索引排序的键,然后使用正确的键索引部分字典。

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let keys = sections.keys.sorted()
    let key = keys[section]
    guard let rows = sections[key] else {
        return 0
    }
    return rows.count
}
相关问题