Kugutsumen
Kugutsumen

Reputation: 936

How to hide scope buttons properly

Initial state:

Initial state

sb.showsScopeBar is set to false

searchBarShouldBeginEditing make the scope buttons appears when the search bar is activated:

func searchBarShouldBeginEditing(_ sb: UISearchBar) -> Bool {
        sb.setShowsCancelButton(true, animated: true)
        sb.scopeButtonTitles = scopeButtonTitles
}

enter image description here

Tapping the cancel button, hides the scope buttons properly and we are back to the original state.

N.B. This is the default behaviour and our searchBarCancelButtonClicked is not doing anything apart from restoring the previous query text if necessary.

Initial state

Now comes the annoying bits...

If I put

sb.setShowsCancelButton(false, animated: true)

in either searchBarShouldEndEditing or searchBarTextDidEndEditing, the cancel button goes away but the scope buttons just shrink:

enter image description here

Adding sb.scopeButtonTitles = nil makes the scope buttons go away but then the search bar doesn't resize :

enter image description here

Calling sb.sizeToFit() doesn't seem to help at all... using sb.showsScopeBar breaks the search bar UI completely.

Upvotes: 1

Views: 78

Answers (1)

Kugutsumen
Kugutsumen

Reputation: 936

Found a solution!

To simulate the behaviour of pressing the cancel button (hide the scope buttons and resize the search bar):

func searchBarTextDidEndEditing(_ sb: UISearchBar) {
    sb.setShowsCancelButton(false, animated: true)
    searchController?.isActive = false
}

We don't need to set sb.scopeButtonTitles to nil.

Upvotes: 1

Related Questions