【发布时间】:2019-08-15 16:43:00
【问题描述】:
我有一个这种形式的数据源:
struct Country {
let name: String
}
其他属性不会在这个阶段发挥作用,所以让我们保持简单。
我已将 ViewController 和 TableViewDataSource 分开在两个单独的文件中。数据源代码如下:
class CountryDataSource: NSObject, UITableViewDataSource {
var countries = [Country]()
var filteredCountries = [Country]()
var dataChanged: (() -> Void)?
var tableView: UITableView!
let searchController = UISearchController(searchResultsController: nil)
var filterText: String? {
didSet {
filteredCountries = countries.matching(filterText)
self.dataChanged?()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredCountries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let country: Country
country = filteredCountries[indexPath.row]
cell.textLabel?.text = country.name
return cell
}
}
如您所见,已经有一个过滤机制。 这是视图控制器最相关的部分:
class ViewController: UITableViewController, URLSessionDataDelegate {
let dataSource = CountryDataSource()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.tableView = self.tableView
dataSource.dataChanged = { [weak self] in
self?.tableView.reloadData()
}
tableView.dataSource = dataSource
// Setup the Search Controller
dataSource.searchController.searchResultsUpdater = self
dataSource.searchController.obscuresBackgroundDuringPresentation = false
dataSource.searchController.searchBar.placeholder = "Search countries..."
navigationItem.searchController = dataSource.searchController
definesPresentationContext = true
performSelector(inBackground: #selector(loadCountries), with: nil)
}
loadCountries 用于获取 JSON 并在 dataSource.countries 和 dataSource.filteredCountries 数组中加载表格视图。
现在,如何在不破坏这一切的情况下获得像联系人应用程序那样的索引排序规则?
我尝试了几个教程,没有一个工作,因为他们需要一个 class 数据模型或视图控制器内的所有内容。
所有解决方案都尝试了崩溃(最坏的情况)或不加载正确的数据或无法识别它......
我需要一些帮助。 谢谢
【问题讨论】:
-
请search。有很多相关的问题
-
我知道 :-( ...但它们都很老了,其中大多数包括 Objective-C。我想知道是否可以使用数据作为结构。
-
是的,有可能。
-
能否请您指出一个可以解决此问题的问题? (我在等待时正在查看您的链接)...我保证如果找到问题我会关闭它,但我在写之前搜索过...
-
具体建议取决于您的设计。请阅读我的搜索查询中的答案。
标签: ios swift uitableview sorting uilocalizedcollation