Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar stretches text when it begins editing

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

enter image description here

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.

like image 843
vfn Avatar asked Aug 06 '15 03:08

vfn


1 Answers

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.

like image 76
Alex Pretzlav Avatar answered Nov 06 '22 07:11

Alex Pretzlav