UILocalizedIndexedCollation的用法
2018-01-09 本文已影响8人
yehkong
序言:UILocalizedIndexedCollation的典型应用场景是:当TableView等列表视图数据很多,需要快速定位到某一分类(比如按字母排序的),可以在列表右侧设置分类索引,通过索引快速定位到需要的数据。
- 先看下这个类的API,内容较少,全部贴出来进行说明用法。
//类方法,返回“单例”
open class func current() -> Self
//根据环境自动返回“分组的标题<数组>”,可以从这里赋值给各分组的标题,配合UITableViewDataSource方法tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? 使用
open var sectionTitles: [String] { get }
//根据环境自动返回“分组的索引<数组>”,经常跟上面返回的是一样的,常常配合UITableViewDataSource方法sectionIndexTitles(for tableView: UITableView) -> [String]?使用
open var sectionIndexTitles: [String] { get }
//根据索引返回分组号,就是定义点击右边索引跳转到对应分组的过程,常常配合UITableViewDataSource方法tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int使用
open func section(forSectionIndexTitle indexTitleIndex: Int) -> Int
//根据对象(列表数组展示的对象)的指定方法进行分组,返回分组号
open func section(for object: Any, collationStringSelector selector: Selector) -> Int
//根据对象分组的指定方法进行重新排序,返回排序后的数组
open func sortedArray(from array: [Any], collationStringSelector selector: Selector) -> [Any]
- 以下是列表数组准备的方法
func sortData(From sourceDataArr : Array<Any>) -> Array<Any> {
let indexedCollation = UILocalizedIndexedCollation.current()
let sectionCount = indexedCollation.sectionIndexTitles.count
let sortedDataArr = NSMutableArray.init(capacity: sectionCount)
//初始化数组“框架”(数组装数组)
for _ in 0 ..< sectionCount {
sortedDataArr.add(NSMutableArray())
}
//将原数据根据指定方法放入到分组中
for object in sourceDataArr {
let section = indexedCollation.section(for: object, collationStringSelector: #selector(MyDivideMethod))
sortedDataArr.object(at: section).add(object)
}
//对各分组按指定方法进行排序
for i in 0 ..< sectionCount {
let sortedSubArr = indexedCollation.sortedArray(from: sortedDataArr.object(at: section), collationStringSelector: #selector(MySortMethod))
sortedDataArr.replaceObject(at: i, with: sortedSubArr)
}
return sortedDataArr as Array
}