Swift - 给表格UITableView添加索引功能(快速定位)
(本文代码已升级至Swift4)
要实现索引,我们只需要两步操作:
(1)实现索引数据源代理方法
(2)响应点击索引触发的代理事件
效果图如下:

代码如下:
import UIKit
class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource{
var tableView:UITableView?
var adHeaders:[String] = ["a","b","c","d","e"]
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
//创建表视图
self.tableView = UITableView(frame:self.view.frame,
style:.grouped)
self.tableView!.delegate = self
self.tableView!.dataSource = self
//创建一个重用的单元格
self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(self.tableView!)
}
//实现索引数据源代理方法
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return adHeaders
}
//点击索引,移动TableView的组位置
func tableView(_ tableView: UITableView,
sectionForSectionIndexTitle title: String, at index: Int) -> Int {
var tpIndex:Int = 0
//遍历索引值
for character in adHeaders{
//判断索引值和组名称相等,返回组坐标
if character == title{
return tpIndex
}
tpIndex += 1
}
return 0
}
//设置分区数
func numberOfSections(in tableView: UITableView) -> Int {
return adHeaders.count;
}
//返回表格行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
// UITableViewDataSource协议中的方法,该方法的返回值决定指定分区的头部
func tableView(_ tableView: UITableView, titleForHeaderInSection
section: Int) -> String? {
var headers = self.adHeaders
return headers[section]
}
//设置分组尾的高度(将分组尾的高度设置为 0.01,消除分组尾空间)
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int)
-> CGFloat {
return 0.01
}
//将分组为设置为一个空的View(否则iOS11系统下光设个高度没用)
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int)
-> UIView? {
return UIView()
}
//创建各单元显示内容(创建参数indexPath指定的单元)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
//为了提供表格显示性能,已创建完成的单元需重复使用
let identify:String = "cell"
//同一形式的单元格重复使用,在声明时已注册
let cell = tableView.dequeueReusableCell(withIdentifier: identify, for: indexPath)
as UITableViewCell
cell.accessoryType = .disclosureIndicator
let secno = indexPath.section
cell.textLabel?.text = self.adHeaders[secno]+String(indexPath.item)
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

swift每次更新,站长每次都要辛苦的重新更新文章里面的代码,看到那句“否则iOS11系统下光设个高度没用”,觉得真不容易呀,我自己写博客应该是懒得更新了,给站长点赞
大神,右侧的列表没有出现啊?请问是什么原因?