【发布时间】:2015-11-16 22:16:57
【问题描述】:
我有一个如下所示的 Dictionary 数据结构,我试图在我的 TableViewController 中对它们进行分组,以便 A 组显示以 title = A 开头的 MyData 并在同时显示 sectionIndexTitlesForTableView 以及从 Title 获得的可用字母。
[这就是我想要实现的]
我试图从我的字典中的标题元素中删除所有第一个字母,并使用下面的代码将它们保存在一个集合中,但是当我运行我的应用程序时,我的表中出现了重复的结果。
我对 swift 还是很陌生,很高兴得到指导,了解如何实现这一目标。
这是我的字典数据:
var data: [[String:AnyObject]] =
[
[
"id": "1",
"title": "A Title",
"alphabet": "A",
"Detail": "This is a String"
],
[
"id": "2",
"title": "A Title Again",
"alphabet": "A",
"Detail": "This is a String"
],
[
"id": "3",
"title": "B Title",
"alphabet": "B",
"Detail": "This is a String"
],
[
"id": "4",
"title": "B Title Again",
"alphabet": "B",
"Detail": "This is a String"
]
]
这是我的尝试:
class Index: UITableViewController {
var MyData = data
var letters = Set<String>()
override func viewDidLoad() {
super.viewDidLoad()
for element in MyData {
var title = element["title"] as? String
let letter = title?.substringToIndex(advance(title!.startIndex, 1))
letters.insert(letter!)
}
MyData = MyData.sort { element1, element2 in
let title1 = element1["title"] as? String
let title2 = element2["title"] as? String
return title1 < title2
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return letters.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.MyData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell?
cell!.textLabel?.text = (MyData[indexPath.row]["title"] as! String)
return cell!
}
【问题讨论】:
标签: ios xcode swift cocoa-touch xcode7-beta5