【问题标题】:How can I order my UITableView Alphabetically?如何按字母顺序订购我的 UITableView?
【发布时间】:2017-03-10 14:00:19
【问题描述】:

我创建了一个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
}

【问题讨论】:

  • 请提供您用于读取文本文件的代码、文本文件本身以及表格视图数据源。
  • 编辑了它@George Green
  • 字典未排序,因此当您调用Array(filtereddictAbteilungen.keys)[indexPath.row] 时,它会根据您的字典键创建一个数组,但您不对它们进行排序。您最好创建一个简单的结构来存储您的数据(而不是键值对)并在创建时对其进行一次排序。将在一分钟内发布如何做到这一点。
  • 请参阅下面@Oleg 的回答,它为您提供了一个可在数据源中使用的元组值的排序列表。
  • 请不要破坏您的帖子

标签: ios arrays swift uitableview


【解决方案1】:

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

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

例子:

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

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

【讨论】:

  • 我的数据源是一个 txt 文件,字典名为“dictAbteilungen” 数组“filtereddictAbteilungen”只是在使用搜索栏搜索内容后应该显示的数组。我仍然不知道该怎么做:(
  • 先尝试对dictAbteliungen进行排序
  • 好的,我会帮你的。现在这样做 let sortedArray = dictAbteilungen.sorted(:by {$0.0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 2023-04-04
相关资源
最近更新 更多