Trev14
Trev14

Reputation: 4116

Jittery Search Bar Cancel / End Editing Animation

I have a SearchBar and am trying to make it behave like one you'd see in the iPhone settings. When it's tapped the animation smoothly transitions the magnifying glass from the middle of the search bar to the left side of the search bar & smoothly brings in the cancel button. However, when I press cancel the animation freezes up then jumps back to normal, with the search icon in the middle of the bar and the cancel button hidden (see GIF preview). Is something in my code making this happen? This is the search bar code:

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(false, animated: true)
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    self.view.endEditing(true)
    searchBar.setShowsCancelButton(false, animated: true)
}

enter image description here

Upvotes: 3

Views: 1441

Answers (1)

Matthew Reilly
Matthew Reilly

Reputation: 619

Put your necessary code in

public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool

Not sure why you have to do it in shouldEnd for hiding the button but didBegin for showing

public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(true, animated: true)
}

public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
    searchBar.setShowsCancelButton(false, animated: true)
    return true
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
}

enter image description here

Upvotes: 6

Related Questions