3

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

Suhaib
  • 2,031
  • 3
  • 24
  • 36
Trev14
  • 3,626
  • 2
  • 31
  • 40

1 Answers1

6

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

Matthew Reilly
  • 619
  • 6
  • 17
  • Thank you Matthew. I was also wondering, could you share your code for searchBarCancelButtonClicked? That's the one I'm having trouble with now. Thanks! – Trev14 Mar 15 '17 at 16:44
  • 1
    I assume you'd like to "close" the search bar. Resigning the field should work. Edited my post. – Matthew Reilly Mar 16 '17 at 01:18