どうもこんにちは。iOSをメインに開発しているロッキーカナイです。
今日は電話帳でよく見るTableViewのインデックスバーを表示してみようと思います!UITableViewDataSourceのデリゲートメソッドを定義すると表示されます。
UITableViewDataSourceのメソッドを定義
1 2 3 4 5 6 7 8 9 10 |
extension ViewController { func sectionIndexTitles(for tableView: UITableView) -> [String]? { return list } func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { self.tableView.scrollToRow(at: [0, index], at: .top, animated: true) return index } } |
これらのデリゲートメソッドを定義するとインデックスバーが表示されます。
sectionIndexTitlesメソッドでは、表示させる文字配列を返します。
tableView:sectionForSectionIndexTitleメソッドはタップされたindexPathが入るので、そこにセル移動するようにscrollToRowを呼んでます。
インデックスバーの設定
1 2 3 4 5 6 7 8 |
// 文字色 self.tableView.sectionIndexColor = UIColor.black // 背景色 self.tableView.sectionIndexBackgroundColor = UIColor.white // トラッキング中の背景色 self.tableView.sectionIndexTrackingBackgroundColor = UIColor.blue |
インデックスバーの文字色、背景色、トラッキング時の背景色の設定が可能です。
表示

表示自体はすごく簡単でしたー!
以上!!
ABOUT ME
