Skip to content

Commit d4a8d66

Browse files
committed
Added HAX for hiding scope bar while scrolling to allow iOS to collapse the search bar naturally
1 parent 3e8e2f9 commit d4a8d66

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

SearchController/ViewController.swift

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ class ViewController: UITableViewController {
66

77
override func viewDidLoad() {
88
super.viewDidLoad()
9-
9+
definesPresentationContext = true
1010
searchController.searchBar.scopeButtonTitles = ["Scope 1", "Scope 2"]
11+
searchController.searchBar.searchBarStyle = .minimal
12+
searchController.obscuresBackgroundDuringPresentation = false
1113
searchController.searchBar.showsScopeBar = true
1214
navigationItem.searchController = searchController
1315
}
@@ -22,5 +24,26 @@ class ViewController: UITableViewController {
2224
return cell
2325
}
2426

25-
}
27+
// HAX: this hides and shows the scope bar appropriately to allow
28+
// the system animation of the search bar to complete properly.
29+
private var lastContentOffset: CGFloat = 0
30+
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
31+
let searchBar = searchController.searchBar
32+
33+
if lastContentOffset > scrollView.contentOffset.y {
34+
// Scrolling down, show the scope bar.
35+
if !searchBar.showsScopeBar && searchBar.frame.size.height > 44 {
36+
searchBar.showsScopeBar = true
37+
}
38+
} else if lastContentOffset < scrollView.contentOffset.y {
39+
// Scrolling up, hide the scope bar to allow the searchBar to collapse
40+
// completely.
41+
if searchBar.showsScopeBar && searchBar.frame.size.height <= 44 {
42+
searchBar.showsScopeBar = false
43+
}
44+
}
45+
46+
lastContentOffset = scrollView.contentOffset.y
47+
}
2648

49+
}

0 commit comments

Comments
 (0)