I like the smell of Swift in the morning…

How to fade in a UITableView section index when the user scrolls

Posted: | Author: | Filed under: iOS, Swift | Tags: | No Comments »

When you have a UITableView with a lot of sections a section index can be very useful to jump quickly between sections. A good example for this is you iPhone’s address book.

But sometimes you want to hide the section index until the user scrolls the table view. The problem is that you can neither hide or show the section index directly nor officially access the UIView that holds the section index.

However there is a little trick to fade the section index in and out. UITableView has two methods that allow you to set the background and the text color of the section index. When you change the alpha of those two colors according to the UITableView’s contentOffset you can fade the section index when the user scrolls:

func scrollViewDidScroll(scrollView: UIScrollView) {
    let fadeInDistance: CGFloat = 100
    var alpha: CGFloat = 1
    if scrollView.contentOffset.y < 1 {
        alpha = 0
    } else if scrollView.contentOffset.y >= 1 && scrollView.contentOffset.y < fadeInDistance {
        alpha = scrollView.contentOffset.y / fadeInDistance
    tableView.sectionIndexColor = UIColor(red: 0, green: 0, blue: 0, alpha: alpha)
    tableView.sectionIndexBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: alpha)

To initially hide the section index you have to set those two colors to UIColor.clearColor() in viewDidLoad:

func viewDidLoad() {
   tableView.sectionIndexColor = UIColor.clearColor()
   tableView.sectionIndexBackgroundColor = UIColor.clearColor()