序言:UILocalizedIndexedCollation的典型應(yīng)用場景是:當(dāng)TableView等列表視圖數(shù)據(jù)很多莫杈,需要快速定位到某一分類(比如按字母排序的),可以在列表右側(cè)設(shè)置分類索引傍药,通過索引快速定位到需要的數(shù)據(jù)登失。
- 先看下這個類的API懦铺,內(nèi)容較少担败,全部貼出來進行說明用法。
//類方法霹菊,返回“單例”
open class func current() -> Self
//根據(jù)環(huán)境自動返回“分組的標(biāo)題<數(shù)組>”,可以從這里賦值給各分組的標(biāo)題剧蚣,配合UITableViewDataSource方法tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? 使用
open var sectionTitles: [String] { get }
//根據(jù)環(huán)境自動返回“分組的索引<數(shù)組>”,經(jīng)常跟上面返回的是一樣的旋廷,常常配合UITableViewDataSource方法sectionIndexTitles(for tableView: UITableView) -> [String]?使用
open var sectionIndexTitles: [String] { get }
//根據(jù)索引返回分組號鸠按,就是定義點擊右邊索引跳轉(zhuǎn)到對應(yīng)分組的過程,常常配合UITableViewDataSource方法tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int使用
open func section(forSectionIndexTitle indexTitleIndex: Int) -> Int
//根據(jù)對象(列表數(shù)組展示的對象)的指定方法進行分組饶碘,返回分組號
open func section(for object: Any, collationStringSelector selector: Selector) -> Int
//根據(jù)對象分組的指定方法進行重新排序目尖,返回排序后的數(shù)組
open func sortedArray(from array: [Any], collationStringSelector selector: Selector) -> [Any]
- 以下是列表數(shù)組準(zhǔn)備的方法
func sortData(From sourceDataArr : Array<Any>) -> Array<Any> {
let indexedCollation = UILocalizedIndexedCollation.current()
let sectionCount = indexedCollation.sectionIndexTitles.count
let sortedDataArr = NSMutableArray.init(capacity: sectionCount)
//初始化數(shù)組“框架”(數(shù)組裝數(shù)組)
for _ in 0 ..< sectionCount {
sortedDataArr.add(NSMutableArray())
}
//將原數(shù)據(jù)根據(jù)指定方法放入到分組中
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
}