emacos
emacos

Reputation: 561

UITableView, Search Bar and section index

Hello I was trying to use UITableView, and i added a SearchBar in viewDidLoad method as follows: enter image description here

and a section index bar with the following method: enter image description here

my question is :

1- is possible to push down the index bar so that it does not cover the SearchBar

2- is possible to scroll up the entire tableView in viewDidLoad method to hidden SearchBar at that the startup of the application

enter image description here

Upvotes: 1

Views: 701

Answers (1)

Losiowaty
Losiowaty

Reputation: 8006

I don't know if this is the easiest way to achieve this, but it works.

The first thing would be to not add the search bar as a header view, but rather to have it and a table view added to a separate scroll view. Something like this (margins for ilustratory purposes only) : light blue is the underlying scroll view nested views

This, automatically fixes issue #1 - the index bar is now under the search bar.

Now, because of this nested scroll views (a table view is a subclass of scroll view) if we want to have a smooth scrolling experience, we need to subclass UIScrollView like that :

class InnerScrollView: UIScrollView {
    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer,
        shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
            return true
    }
}

and use this class as our underlying scroll view - either in code, or by setting it in Interface Builder. This makes it so that, when the user scrolls, the search bar will appear/disappear first and then the table view content will scroll smoothly.

As to the initial offset, this will need to be done in viewDidLayoutSubviews, as this is the first place where you can be sure that the scroll views have been setup.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let initalContentOffset = CGPoint(x: 0, y:self.tableView.frame.origin.y)
    self.underlyingScrollView.contentOffset = initalContentOffset

}

Let me know if anything is not clear.

Upvotes: 1

Related Questions