ios – swift中表格视图中的字母部分

我有一个按字母顺序排列的名称列表,现在我要在表视图中显示这些名称.我正在努力为每个字母分组这些名字.

我的代码如下所示:

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
}

这一切都非常好,除了分组,使我的表视图最终如下所示:

所以我知道你应该能够使用过滤的函数在一个数组,但我不明白如何实现它.

任何关于如何进行的建议将不胜感激.

解决方法

您可以将带有名称的数组放入具有字母键的字典中.

例如

var names = ["a": ["and","array"],"b": ["bit","boring"]]; // dictionary with arrays setted for letter keys

那么您需要以下一个方式访问您的字典中的值

func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int{
    return names[usernames[section]].count; // maybe here is needed to convert result of names[...] to NSArray before you can access count property
}

func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

    let cellID = "cell"

    let cell: UITableViewCell = self.tv.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell

    cell.textLabel?.text = names[usernames[indexPath.section]][indexPath.row]; // here you access elements in arrray which is stored in names dictionary for usernames[indexPath.section] key

return cell
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...