ios - 如何按字母顺序排列我的 UITableView?

标签 ios arrays swift uitableview

我创建了一个 UITableView,它从 txt.file 中获取数据。 然而,尽管 txt-File 是按字母顺序排序的,但 UITableView 却不是。

有人知道如何按字母顺序排序吗?

我正在使用 Swift 3 和 Xcode 8。

var dictA = [String:String]()
var filtereddictA = [String:String]()
var visibleA = [ String ]()
var searchController =  UISearchController()

override func viewDidLoad() {
    super.viewDidLoad()

    let path = Bundle.main.path(forResource: "a", ofType:"txt")

    let filemgr = FileManager.default
    if filemgr.fileExists(atPath: path!) {
        do {
            let fullText = try String(contentsOfFile: path! ,encoding: String.Encoding.utf8)

            let readings = fullText.components(separatedBy: "\n")

            for abteilungen in readings {
                let aData = abteilungen.components(separatedBy: "\t")

                if abteilungenData.count > 1 {
                    dictA[aData[0]] = aData[1]
                }
            }
            filtereddictA = dictA

        } catch let error {
            print("Error: \(error)")
        }

        searchController = UISearchController (searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()

        tableView.tableHeaderView = searchController.searchBar

        definesPresentationContext = true
    }

    self.title = "A"

}

// MARK: - Table view data source

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

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filtereddictA.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let key = Array(filtereddictA.keys)[indexPath.row]

    cell.textLabel?.text = key
    cell.detailTextLabel?.text = filtereddictA[key]

    return cell
}

@available(iOS 8.0, *)
public func updateSearchResults(for searchController: UISearchController) {
    guard let searchText = searchController.searchBar.text?.lowercased() else {
        return
    }

    let keyPositions = Array(filtereddictA.keys)
    filtereddictA = [:]
    var removeArray = [ IndexPath ]()
    var addArray = [ IndexPath ]()
    for ab in dictA {
        if abteilung.key.lowercased().range(of: searchText) != nil || a.value.lowercased().range(of: searchText) != nil || searchText.isEmpty {
            filtereddictA[ab.key] = ab.value
        } else {
            if let index = keyPositions.index(of: abteilung.key) {
                removeArray.append(IndexPath(row: index, section: 0))
            }
        }
    }

    if removeArray.count > 0 {
        removeArray.sort(by: { (p1,p2) -> Bool in
            return p1.row > p2.row
        })
        tableView.deleteRows(at: removeArray, with: .bottom)
    }
    var i = 0
    for ab in filtereddictA.keys {
        if !keyPositions.contains(ab) {
            addArray.append(IndexPath(item: i, section: 0))
        }
        i += 1
    }
    if addArray.count > 0 {
        addArray.sort(by: { (p1,p2) -> Bool in
            return p1.row < p2.row
        })
        tableView.insertRows(at: addArray, with: .bottom)
    }
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filtereddictA.count
}

最佳答案

您应该为数据源中的元素设置正确的顺序。 我可以假设 filtereddictAbteilungen 是您作为数据源的字典。

所以首先对其进行排序,然后通过 tableView 进行填充。

例子:

let dictionary = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

let sortedKeys = dictionary.sorted(by: { $0.0 < $1.0 })

关于ios - 如何按字母顺序排列我的 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42720184/

相关文章:

检查结构数组中非空字符串的数量;将 NULL 值分配给结构数组中的 char 数组

arrays - 如何快速创建对象的数组列表

在函数内部捕获 Swift pass 错误

objective-c - 没有协议(protocol)的 iOS 委托(delegate)?

ios - 在 Airplay 的 UIWebview 背景下播放视频

ios - 在核心数据中创建关注者关注模型

javascript - 通过逗号和 "and"连接数组

ios - 使用蓝牙时如何设置超时间隔

具有自定义高度的iOS drawRect

c - 为什么这个二分搜索会给我一个无限循环?