I have an instance of a UISearchBar added to the title view of a UINavigationBar. When there is text already set and the search bar starts editing it resizes its contents to allow space for the Cancel button, although, the resulting animation stretches the text, as showed in the gif below
Is there anything that can be done to avoid this defect effect? I have tried to remove the text and then to add it back a few moments later, although it works, it is not an elegant solution.
Update
Based on @Paruru's answer I tried to anticipate the animation of the Cancel
button and it doesn't look bad. What I did is that I force the presentation of the Cancel
button on searchBarShouldBeginEditing:
extension SearchViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
if searchBar.text?.isEmpty == false {
// This avoids the text being stretched by the UISearchBar.
searchBar.setShowsCancelButton(true, animated: true)
}
return true
}
}
The end result is what I want to achieve, the animation without the text being stretched. I consider this to be a workaround, and so I'll wait for other answers as this code might not be future proof.
Your updated solution works well, except it stops the "Search" placeholder from being animated to the left when the Cancel button appears while there is no text. Checking searchBar.text
restores the animation:
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
// This avoids the text being stretched by the UISearchBar.
if searchBar.text?.isEmpty == false {
searchBar.setShowsCancelButton(true, animated: true)
}
return true
}
I suspect this may only be an issue for the Minimal
UISearchBarStyle
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With