在桌子视图的按字母顺序的部分在迅速

mar*_*tin 19 uitableview nsarray 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
}
Run Code Online (Sandbox Code Playgroud)

这一切都很好,除了使我的表视图结束的分组如下:

在此输入图像描述

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

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

vad*_*ian 18

在Swift 4中,Dictionary(grouping:by :)被引入以通过任意谓词将序列归类为字典。

本示例将分组字典映射到自定义结构 Section

struct Section {
    let letter : String
    let names : [String]
}

...

let usernames = ["John", "Nancy", "James", "Jenna", "Sue", "Eric", "Sam"]

var sections = [Section]()

override func viewDidLoad() {
    super.viewDidLoad()

    // group the array to ["N": ["Nancy"], "S": ["Sue", "Sam"], "J": ["John", "James", "Jenna"], "E": ["Eric"]]
    let groupedDictionary = Dictionary(grouping: usernames, by: {String($0.prefix(1))})
    // get the keys and sort them
    let keys = groupedDictionary.keys.sorted()
    // map the sorted keys to a struct
    sections = keys.map{ Section(letter: $0, names: groupedDictionary[$0]!.sorted()) }
    self.tableView.reloadData()
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cellID = "cell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
    let section = sections[indexPath.section]
    let username = section.names[indexPath.row]
    cell.textLabel?.text = username
    return cell
}

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

func numberOfSectionsInTableView(tableView: UITableView) -> Int{
    return sections.count
}

func sectionIndexTitles(for tableView: UITableView) -> [String]? {
    return sections.map{$0.letter}
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sections[section].letter
}
Run Code Online (Sandbox Code Playgroud)


Rao*_*Rao 10

这是我最近以编程方式在Swift中的tableView中实现排序列表的方式,

import UIKit

class BreedController: UITableViewController{

    var breeds = ["A": ["Affenpoo", "Affenpug", "Affenshire", "Affenwich", "Afghan Collie", "Afghan Hound"], "B": ["Bagle Hound", "Boxer"]]

    struct Objects {
        var sectionName : String!
        var sectionObjects : [String]!
    }

    var objectArray = [Objects]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")
        // SORTING [SINCE A DICTIONARY IS AN UNSORTED LIST]
        var sortedBreeds = sorted(breeds) { $0.0 < $1.0 }
        for (key, value) in sortedBreeds {
            println("\(key) -> \(value)")
            objectArray.append(Objects(sectionName: key, sectionObjects: value))
        }
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return objectArray.count
    }

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
        // SETTING UP YOUR CELL
        cell.textLabel?.text = objectArray[indexPath.section].sectionObjects[indexPath.row]
        return cell
    }

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return objectArray[section].sectionName
    }


}
Run Code Online (Sandbox Code Playgroud)


Ser*_*kar 2

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

例如

var names = ["a": ["and", "array"], "b": ["bit", "boring"]]; // dictionary with arrays setted for letter keys
Run Code Online (Sandbox Code Playgroud)

那么你需要以下面的方式访问字典中的值

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
}
Run Code Online (Sandbox Code Playgroud)