【发布时间】:2015-01-22 11:30:44
【问题描述】:
我有一个按字母顺序排序的名称列表,现在我想在表格视图中显示这些名称。我正在努力为每个字母分组这些名称。
我的代码如下所示:
let sections:Array<AnyObject> = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
var usernames = [String]()
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cellID = "cell"
let cell: UITableViewCell = self.tv.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell
cell.textLabel?.text = usernames[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return usernames.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return 26
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]!{
return self.sections
}
func tableView(tableView: UITableView,
sectionForSectionIndexTitle title: String,
atIndex index: Int) -> Int{
return index
}
func tableView(tableView: UITableView,
titleForHeaderInSection section: Int) -> String?{
return self.sections[section] as? String
}
这一切都很好,除了分组使我的表格视图最终变成这样:
所以我知道你应该可以在数组中使用过滤函数,但我不明白如何实现它。
任何关于如何进行的建议将不胜感激。
【问题讨论】:
-
cell.textLabel?.text = usernames[indexPath.row]是您的问题根源。您不断用完全相同的数据填充每个部分。 -
是的,我只需要正确过滤用户名数组:)
-
虽然下面有一些尝试-我发现这个objective-c更可靠github.com/chrisladd/CGLAlphabetizer/blob/master/Example/…
标签: ios uitableview swift nsarray