Stu*_*rtM 3 uitableview uiscrollview swift
我正在尝试为联系人表视图添加一些节标题.我有一个联系人列表,Array其中可能是这样的:
Bill Apple
Borat
Steve Test
我添加了以下内容:
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let currentCollation = UILocalizedIndexedCollation.currentCollation() as UILocalizedIndexedCollation
let sectionTitles = currentCollation.sectionTitles as NSArray
return sectionTitles.objectAtIndex(section) as? String
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
let currentCollation = UILocalizedIndexedCollation.currentCollation() as UILocalizedIndexedCollation
return currentCollation.sectionIndexTitles as [String]
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
let currentCollation = UILocalizedIndexedCollation.currentCollation() as UILocalizedIndexedCollation
return currentCollation.sectionForSectionIndexTitleAtIndex(index)
}
Run Code Online (Sandbox Code Playgroud)
这会让AZ标题显示出来.但是,由于只有一个部分和一个数组保持联系人,实际功能不起作用.
我们应该把它分类Array成某种字母表Array吗?这样它有多个部分?或者有更简单的方法来解决这个问题吗?
小智 6
我们应该将Array排序成某种字母数组吗?这样它有多个部分?
是.
您为节索引添加了委托方法,但未显示任何实际执行排序规则的代码.
以下是来自NSHipster的一些示例代码,展示了如何使用UILocalizedIndexedCollation将对象数组(例如,联系人)整理成对象部分的数组(例如,按部分分组的联系人):
let collation = UILocalizedIndexedCollation.currentCollation()
var sections: [[AnyObject]] = []
var objects: [AnyObject] = [] {
didSet {
let selector: Selector = "localizedTitle"
sections = Array(count: collation.sectionTitles.count, repeatedValue: [])
let sortedObjects = collation.sortedArrayFromArray(objects, collationStringSelector: selector)
for object in sortedObjects {
let sectionNumber = collation.sectionForObject(object, collationStringSelector: selector)
sections[sectionNumber].append(object)
}
self.tableView.reloadData()
}
}
Run Code Online (Sandbox Code Playgroud)
您还需要更新剩余的tableView委托以使用该sections数组:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let contact = sections[indexPath.section][indexPath.row]
...
}
Run Code Online (Sandbox Code Playgroud)
仅供参考,您可以通过将collation属性分配给视图控制器来简化代理代码,而不是在每个委托方法中为(当前)排序规则重复声明局部变量.例如:
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String {
return collation.sectionTitles[section]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3472 次 |
| 最近记录: |